简体   繁体   中英

setState(…): Can only update a mounted or mounting component even if component is mounted

I am using react latest version, I receive the following error when click a button which run expandMenu()

Here tracing the lifecycle:

constructor
componentWillMount
render
componentDidMount
componentWillReceiveProps
render
componentWillReceiveProps
render
componentWillReceiveProps
render
expandMenu <<< click on the button - boom error!

AFAIK the component is mounted when running expandMenu() , which make the error to be ambiguous. What could cause the problem and how to fix it?

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted

 export class Menu extends React.Component<Props, State> { constructor(props: Props) { super(props) this.state = { showPath: true, selectedItemIdx: 1, } } componentWillReceiveProps(nextProps: Props) { const { items } = nextProps this.setState({ selectedItemIdx: items.length - 1, }) } componentWillMount() { console.debug('componentWillMount') } componentDidMount() { console.debug('componentDidMount') } componentWillUnmount() { console.debug('componentWillUnmount') } expandMenu = () => { console.debug('expandMenu') const { items } = this.props if (items.length > 1) { this.setState({ showPath: true }) // error here } } itemClickHandler = (idx: number) => { this.expandMenu() } render() { console.debug('render') const { classes } = this.props return ( <div className={classes.root}> <ButtonBase className={classes.title} onClick={() => { this.itemClickHandler(idx) }} > ))} </div> ) } } 

问题与react-hot-loader有关,我必须将其从项目依赖项中删除。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM