React異步請(qǐng)求數(shù)據(jù)出現(xiàn)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.

大概意思就是我們可能對(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)_isMountedtrue即還未被卸載,才執(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
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本文解讀了react生命周期的源碼,如果你還是個(gè)入門的小白,當(dāng)然可以忽略源碼,看一看作者寫的demo。也可以明白生...
    Dabao123閱讀 1,402評(píng)論 0 4
  • 自己最近的項(xiàng)目是基于react的,于是讀了一遍react的文檔,做了一些記錄(除了REFERENCE部分還沒開始讀...
    潘逸飛閱讀 3,741評(píng)論 1 10
  • 組件的生命周期方法分以下三個(gè)階段。 Mounting當(dāng)創(chuàng)建組件的實(shí)例并將其插入到DOM中時(shí),將調(diào)用這些方法:con...
    _八神光_閱讀 1,216評(píng)論 0 0
  • 這兩天呆在家里,多虧有它做伴兒, 稍有空氣異味兒,立馬發(fā)紅色警報(bào), 一會(huì)兒又變黃色,最后恢復(fù)到綠色, 清除室內(nèi)異味...
    夢(mèng)想917閱讀 257評(píng)論 0 2
  • 人的內(nèi)心永遠(yuǎn)是無(wú)限制出新的泉眼,在不斷的矛盾中求得更多的未知事物。 比如說(shuō),我從不知道我是這樣的人,而今已經(jīng)變成了...
    無(wú)嘆閱讀 395評(píng)論 0 0

友情鏈接更多精彩內(nèi)容