Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a me

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重写,核心
  }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值