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