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.这个报错的原因是因为自己使用mobx时,起初是好用的。然后切换成另外一个身份进入时,就报错了。是因为之前登录的身份里面的autorun函数一直在观察着,你只是组件已经销毁了而已。然后你再次换另外一个身份登进去之后,又再一次的执行了autorun,所以等于就是两个autorun同时执行着,才会导致报错。
解决方案:
mobx里面的autorun是支持返回一个函数,可以将autorun返回值赋值给一个定义在this上的一个属性,然后当你离开的时候,利用componentWillUnmount生命周期直接销毁。
componentDidMount() {
this.myCancel =autorun(()=>{
this.setState({
isShow:store.get("isShow")
})
})
}
componentWillUnmount(){
this.myCancel() //取消观察
}
还有一个原因也会报同样的错,就是在网速慢的情况的,你去请求数据。然后看没有数据时,又返回出去了,等于你将组件卸载了,可过了一会数据回来之后,也会报同样的错。
解决方案:当组件销毁时,取消ajax请求。
componentDidMount() {
var username = JSON.parse(localStorage.getItem("users")).username
Axios.get(`http://localhost:8000/articles?author=${username}`).then(res=>{
this.setState({
datalist:res.data
})
})
}
componentWillUnmount(){
this.setState = ()=>{} //直接将setState重写,核心
}