我对React-Native有问题(我使用的是Expo)。
我在componentDidMount()中传递了一个函数,该函数调用动作(redux)以从API检索数据。
当我关闭应用程序并再次打开它时,出现此错误:
警告:无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,取消%s。%s(componentWillUnmount方法)中的所有订阅和异步任务
我尝试了几种方法:
https://github.com/material-components/material-components-web-react/issues/434
React-Native: Warning: Can't perform a React state update on an unmounted component
以及我在Stack上发现的其他类似方法,但没有任何效果,并且错误仍然存在。
以前有人遇到过这个问题吗?
您能帮我解决这个问题吗?
答案 0 :(得分:0)
我不确定react-native是否会与reactjs出现相同的问题,但是当在我的react应用上时,它抱怨内存泄漏错误,我只需要添加AbortController()。
您可以尝试这样的事情
abortController = new AbortController();
componentDidMount() {
fetch('url', {
signal: this.abortController.signal,
}).then((res) => {
// do something
}).catch((err) => {
if (err.name === 'AbortError') {
// throw error;
}
})
componentWillUnmount() {
this.abortController.abort();
}
}
希望这会有所帮助。