Can’t call setState (or forceUpdate) on an unmounted component 警告处理方法

Can’t call setState (or forceUpdate) on an unmounted component

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

不能在已经被销毁的组件中调用setState()方案
出现场景:跳转路由 当前组件被销毁 组件内部还存在异步操作对state的状态信息 比如http请求,定时器setTimeOut更新state

思路就是在组件卸载之前 控制异步不进行setState
解决方案一:组件被销毁之前重写setState方法 不对状态做任何改变
componentWillUnmount(){
this.setState = (state,callback)=>{
return;
};
}
解决方案二:组件被销毁之前 可以setState 销毁之后就不能setState
componentWillMount() {
this._isMounted = true
fetch('网络请求').then (status, response)=>{
if (this._isMounted) {
this.setState({
activityTipsImg: response.data.tips_url,
activityTipsContent: response.data.tips_content
})
}
});
}
componentWillUnmount() {
this._isMounted = false
}
---------------------
作者:SalahMan
来源:CSDN
原文:https://blog.csdn.net/softwarenb/article/details/81123389
版权声明:本文为博主原创文章,转载请附上博文链接!

上一篇:SPA和MVVM设计思想


下一篇:20155219付颖卓《网络对抗》MSF基础应用实验