React異步請求數據出現setState(...): Can only update a mounted or mounting component...

Warning: 
setState(...): 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 xxx component.

大概意思就是我們可能對一個沒有裝載的組件執行了setState()操作,在React的官網裏有一個解決這個辦法的方案,isMounted
原因:

Such situations most commonly occur due to callbacks, 
when a component is waiting for some data and gets unmounted before the data arrives. 
Ideally, any callbacks should be canceled in componentWillUnmount, prior to unmounting.

大概意思是這種情況會出現在callback中,我們的異步請求返回數據之前,組件可能就已經被卸載了,等數據回來再使用setState就會報出上面的警告,所以我們應該手動在componentWillUnmount裏去取消callback在它被unmounting之前。
解決辦法:

Just set a _isMounted property to true in componentDidMount 
and set it to false in componentWillUnmount, and use this variable to check your component's status.

很好理解,我們使用一個標誌位_isMounted,在componentDidMount裏設置爲true,在componentWillUnmount裏設置爲false,僅當_isMountedtrue即還未被卸載,才執行setState()
我的代碼:

componentWillMount() {
        this._isMounted = true
        fetch('網絡請求').then (status, response)=>{
          if (this._isMounted) {
            this.setState({
                activityTipsImg: response.data.tips_url,
                activityTipsContent: response.data.tips_content
            })
          }
        });
}
componentWillUnmount() {
        this._isMounted = false
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章