gpt4 book ai didi

javascript - 无法在未安装的组件上调用 setState(或 forceUpdate)。这是一个空操作,但它表明您的应用程序中存在内存泄漏

转载 作者:行者123 更新时间:2023-11-29 16:36:16 26 4
gpt4 key购买 nike

为什么会出现此错误?

Warning: Can't call setState (or forceUpdate) 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.

postAction.js

export const getPosts = () => db.ref('posts').once('value');

组件:

constructor(props) {
super(props);
this.state = { posts: null };
}

componentDidMount() {
getPosts()
.then(snapshot => {
const result = snapshot.val();
this.setState(() => ({ posts: result }));
})
.catch(error => {
console.error(error);
});
}

componentWillUnmount() {
this.setState({ posts: null });
}

render() {
return (
<div>
<PostList posts={this.state.posts} />
</div>
);
}

最佳答案

正如其他人提到的,componentWillUnmount 中的 setState 是不必要的,但它不应该导致您看到的错误。相反,可能的罪魁祸首是这段代码:

componentDidMount() {
getPosts()
.then(snapshot => {
const result = snapshot.val();
this.setState(() => ({ posts: result }));
})
.catch(error => {
console.error(error);
});
}

因为 getPosts() 是异步的,所以有可能在它解析之前,组件已经卸载。您没有对此进行检查,因此 .then 可以在组件卸载后结束运行。

要处理这个问题,您可以在 willUnmount 中设置一个标志,然后在 .then 中检查该标志:

componentDidMount() {
getPosts()
.then(snapshot => {
if (this.isUnmounted) {
return;
}
const result = snapshot.val();
this.setState(() => ({ posts: result }));
})
.catch(error => {
console.error(error);
});
}

componentWillUnmount() {
this.isUnmounted = true;
}

关于javascript - 无法在未安装的组件上调用 setState(或 forceUpdate)。这是一个空操作,但它表明您的应用程序中存在内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51246815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com