1. 程式人生 > >react警告:setState(...): Cannot update during an existing state transition (such as within `render` or

react警告:setState(...): Cannot update during an existing state transition (such as within `render` or

在使用react的時候,發現一個警告 

Warning: setState(...):Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`

不能在現有狀態轉換期間更新(例如在' render '或其他元件的建構函式中)。渲染方法應該是道具和狀態的純函式;建構函式的副作用是反模式的,但是可以移動到“componentWillMount”

先開始我是這樣寫的:

componentDidMount(){
     AccountStore.listen(this.accountChange);
     this.accountChange();
}

然後在執行的時候,偶爾會出現警告:

setState是非同步執行的,加一個this.mounted控制執行順序:

componentDidMount(){
     this.mounted = true;
     AccountStore.listen(this.accountChange);
     if(this.mounted == true){
          this.accountChange();
     }
}
componentWillUnmount(){
     this.mounted = false
}

警告就沒有了