1.这是报错的消息:
Can’t perform a React state update 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
大概的意思为:我们不能在组件销毁后设置state,防止出现内存泄漏的情况
2.我搜索一番,看到一个发现场景的栗子,觉得比较清晰
//组件B
class TestContainer extends Component{
constructor(){
super()
this.state = {
isShow:true
}
}
render(){
return (
<div>
<button onClick={()=>this.setState({isShow:!this.state.isShow})}>toggle</button>
{!!this.state.isShow&&<Test />}
</div>
)
}
}
//组件A
class Test extends Component{
constructor(){
super()
this.state = {
num:0
}
}
getNum=()=>{
//模拟异步请求
this.timer = setTimeout(()=>{
this.setState({ num: Math.random() })
},3000)
}
render(){
return (
<div onClick={this.getNum} style = {{ width: 100, height: 100, background: 'red' }}>
{this.state.num}
</div>
)
}
}
在本例子中:
当我们点击组件A时,会发送一个异步请求,请求成功后会更新num的值。
当我们点击组件B时,会控制组件的A的卸载与装载
当我们点击组件A后,组件A需要3秒的时间才能获取到数据并重新更新num的值,假如我们在这3秒内点击一次组件B,
表示卸载组件A,但是组件A的数据请求依然还在,当请求成功后,组件A已经不存在,此时就会报这个警告(大概意思就是:你组件都没了,你还设置个啥)
3.解决办法
既然组件销毁后异步请求报错,我们应该在组件销毁的时候将异步请求撤销
componentWillUnmount = () => {
this.setState = (state,callback)=>{
return;
};
}
只需要在组件的生命周期 componentWillUnmount 添加上述内容即可
内容转自 https://segmentfault.com/a/1190000017186299?utm_source=tag-newest