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
,僅當_isMounted
爲true
即還未被卸載,才執行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
}