## React開發遇到的問題匯總
### 2016/2/29 16:20
### 錯誤1: getInitialState里 setState
```
Uncaught Error: Invariant Violation: setState(...): Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.
```
1. 出現原因
由于在 ``getInitialState`` 方法里面調用了 ``this.setState()``方法,導致報這個錯誤
2. 解決方案
``getInitialState`` 里面 設置 ``this.setState()`` 的代碼,放到 ``componentDidMount``里面去
具體可以看:[Stackoverflow的解決方案](http://stackoverflow.com/questions/31420402/why-does-this-error-exist-invariant-violation-cannot-update-during-an-existin)
---
#### 錯誤2:Ajax 處理時,組件已經卸載了的問題
~~~
Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
~~~
**React Ajax,返回數據的時候,組件已經寫在的問題解決方案?**
>描述:Ajax請求還沒有請求結束,組件已經卸載了。 會報錯,告訴你不能對寫在的組件進行 setState 操作。
比如:Ajax請求,發送出去了, 還沒有請求到結果,用戶已經點擊跳轉到其他頁面了。跳轉到其他頁面后, React 組件就卸載了, 去加載另外一個React-router匹配的組件。 這個時候,等AJax 請求結束了, 執行回調方法,對組件進行 setState, 就報錯了。
解決方案:React卸載,就中斷Ajax的請求,這個方法也是官網推薦的。
~~~
componentDidMount(){
//Model.getScriptTypes 封裝的就是一個 $.ajax 方法。 return $.ajax({}) 對象
this.ajaxGetScriptTypes = Model.getScriptTypes(function (result) {
that.setState({scriptTypeData: result.data})
})
}
/**
* 組件卸載前的操作
*/
componentWillUnmount() {
this.ajaxGetScriptTypes.abort();
this.ajaxGetScriptlist.abort();
}
~~~