當咱們在平時切換組件的時候,會遇到這種狀況,若是組件中有異步請求任務,【當接口已經發出請求,可是組件已經銷燬,那麼接口返回數據後bash
會有這麼一個警告app
Warning: 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.
複製代碼
翻譯: 警告:沒法對未安裝的組件執行響應狀態更新。這是一個禁止操做,但它表示應用程序內存泄漏。要修復,請取消componentwillunmount方法中的全部訂閱和異步任務。異步
狀況一: 阻止異步操做async
componentWillUnmount() {
this.setState = (state, callback) => {
return
}
}
複製代碼
狀況一: 清除定時ui
var timer;
...
componentDidMount = () => {
timer = setTimeout(() => {
this.setState({a:123})
},1000)
}
componentWillUnMount = () => {
clearTimeout(timer)
}
複製代碼