react常见组件问题Can't perform a React state update on an unmounted component


在写react组件的时候,会有这个警告

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状态,

  payload:values,
        callback:res=>{
          if(res.code === 0){
            notification.success({
              message: '密码更新成功',
              description: `新密码为 ${res.data}`,
              duration: 0,
            });
            successed&& successed();
              that.setState({
                updatePwdModalVisible:false
              })
            that.getCaptcha();

解决方法:利用生命周期钩子函数:componentWillUnmount,在组件卸载前清除timer

 that.pwdErrorTimer = setTimeout(() => {
              this.setState({
                updatePwdModalVisible:false
              })
            }, 1000);

  

  componentWillUnmount(){
    clearTimeout(this.pwdErrorTimer);
  }

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM