Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the SalesInfo component.
出现这种情况,是因为组件卸载之后,调用了 setState。
通常会出现在以下两个场景:
1.在绑定事件的回调函数调用了 setState,而且在组件卸载时没有清除。
class SalesInfo extends React.Component{
......
componentDidMount(){
document.getElementById('root').addEventListener('click', this.cancelOpen)
}
componentWillUnmount() {
// 只需要在组件卸载前移除事件绑定即可
document.getElementById('root').removeEventListener('click', this.cancelOpen)
}
cancelOpen = () => {
this.setState({
isOpen: false
})
}
......
}
2.异步请求数据调用 setState 方法,在组件已经 unmount 的状态下,请求才完成。
class SalesInfo extends React.Component {
......
componentDidMount() {
this.fetchData()
}
fetchData = () => {
httpFetch({
url: 'xxx',
data:{}
})
.then(() => {
this.setState({...}) // 在组件卸载后,才完成请求进行数据处理
})
}
......
}
解决方法:
https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
在React应用中,当组件卸载后继续调用setState会导致警告。常见原因包括未在组件卸载前移除事件监听器,以及异步操作在组件卸载后才更新状态。解决方法是确保在组件卸载时清理事件监听器,并取消或忽略在卸载后可能触发的setState操作。遵循正确的组件生命周期管理可以避免此类问题。
3449

被折叠的 条评论
为什么被折叠?



