无法对已卸载的组件调用 setState(或forceUpdate)。这是一个空操作,但它表明您的应用程序中存在内存泄漏

2024-02-25

为什么我会收到此错误?

警告:无法在未安装的状态下调用 setState(或forceUpdate) 成分。这是一个空操作,但它表明您的内存泄漏 应用。要修复此问题,请取消所有订阅和异步任务 在 componentWillUnmount 方法中。

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法对已卸载的组件调用 setState(或forceUpdate)。这是一个空操作,但它表明您的应用程序中存在内存泄漏 的相关文章

随机推荐