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”

  解決方法:利用生命周期鈎子函數:componentWillUnmount,在組件卸載前清除timer

 

   // 組件加載完畢 啟動定時器
      settimem: setTimeout(this.iTimer, 3000),


 // 定時器
  iTimer = () => {
    this.setState({
      timer: setInterval(() => {
        this.postuseinfo(sessionStorage.getItem("huihuaid"));
      }, 20000),
    });

// 組件清除時清除定時器
  componentWillUnmount() {
    clearInterval(this.state.timer && this.state.timer);
    clearInterval(this.state.settimem && this.state.settimem);
  }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM