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.
大概意思就是我們可能對(duì)一個(gè)沒有裝載的組件執(zhí)行了setState()操作,在React的官網(wǎng)里有一個(gè)解決這個(gè)辦法的方案,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.
大概意思是這種情況會(huì)出現(xiàn)在callback中,我們的異步請(qǐng)求返回?cái)?shù)據(jù)之前,組件可能就已經(jīng)被卸載了,等數(shù)據(jù)回來(lái)再使用setState就會(huì)報(bào)出上面的警告,所以我們應(yīng)該手動(dòng)在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.
很好理解,我們使用一個(gè)標(biāo)志位_isMounted,在componentDidMount里設(shè)置為true,在componentWillUnmount里設(shè)置為false,僅當(dāng)_isMounted為true即還未被卸載,才執(zhí)行setState()。
我的代碼:
componentWillMount() {
this._isMounted = true
fetch('網(wǎng)絡(luò)請(qǐng)求').then (status, response)=>{
if (this._isMounted) {
this.setState({
activityTipsImg: response.data.tips_url,
activityTipsContent: response.data.tips_content
})
}
});
}
componentWillUnmount() {
this._isMounted = false
}