1、問題bug 1
(
Fetch不能中斷的話 那如何在組件移除之前 移除掉這個異步請求?
)
React中,因為異步操作的關系,組件銷毀后調用了setState(),報警告,怎么解決?
我在componetWillMount中訪問了接口返回數據后,調用了setState,訪問的時候按了后退,導致還沒收到響應就銷毀了組件 ,但是fetch請求沒被結束掉,之后 收到響應就調用了setState(),發出警告。請問這種情況該怎么處理?在unmount中結束fetch嗎?但fetch怎么結束呢?官方文檔好像沒有api
解決方法:
react一直報這個錯誤:
Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
原因:
通常是 react 組件已經從 DOM 中移除,但是我們在組件中做的一些異步操作還未結束,如:接口調用等,當其完成時,執行setState操作,而此時我們已經將改組件dom移除,從而導致上述問題。
解決辦法:
componentWillUnmount(){ // 卸載異步操作設置狀態 this.setState = (state, callback) => { return; } }