首页 > 解决方案 > 无法在未安装的组件上调用 setState(或 forceUpdate)。这是一个无操作,但它表明您的应用程序中存在内存泄漏

问题描述

为什么我会收到此错误?

警告:无法在未安装的组件上调用 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>
  );
}

标签: javascriptreactjsfirebase

解决方案


正如其他人所提到的, 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;
}

推荐阅读