我在两个屏幕成功之间导航,但始终在下面显示警告我:
警告:无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,请取消componentWillUnmount方法中的所有订阅和异步任务
在Alert中(在AwesomeAlert.js:7)
在AwesomeAlert中(在LoadingDialog.js:7)
在LoadingDialog中(在LoginScreen.js:180处)
如何解决?
答案 0 :(得分:1)
您可以在挂载(isMounted
或类似名称)上设置布尔状态标志,然后在false
中将其设置为componentWillUnmount
。在调用引发此警告的函数之前,请检查此标志。
答案 1 :(得分:0)
1),请确保您拥有{strong> event listeners, setTimeouts or setIntervals
中的 componentDidMount
,并且在 componentWillUnmount
侦听器,setTimeouts和setIntervals的示例:
componentDidMount() {
this.myTimer = setTimeout(() => {
// someCode here
}, 7000);
AppState.addEventListener('change', this.handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
clearTimeout(this.myTimer);
}
2)要取消获取,您可以使用以下选项:
选项A:使用AbortController
(我认为AbortController比具有isMounted
变量的旧解决方案好得多)
AbortController示例:
import "abortcontroller-polyfill"; // in RN 0.60+ this will probably not be needed anymore
class App extends React.Component {
constructor() {
const AbortController = window.AbortController;
this.controller = new AbortController();
this.signal = this.controller.signal;
}
componentDidMount() {
const url = "https://myurl.com";
const signal = this.signal;
fetch(url, { signal })
.then(res => res.json())
.then(json => console.log(json))
.catch(err => {
// You can catch the error
// thrown by the polyfill here.
if (err.name == "AbortError") {
console.log("Fetch Aborted");
} else {
//Catch other errors.
}
});
}
componentWillUnmount() {
this.controller.abort();
}
/*--Rest of the code.--*/
}
选项B:使用Axios
并在componentDidMount
中触发取消操作
https://github.com/axios/axios#cancellation
来源:
AbortController代码: https://github.com/facebook/react-native/issues/18115#issuecomment-420766665
How to cancel a fetch on componentWillUnmount
https://developer.mozilla.org/en-US/docs/Web/API/AbortController