首页 > 解决方案 > How to stop Firestore `get` query on componentWillUnmount

问题描述

okay so I'm fetching data from Firestore in componentDidMount but while it's fetching the data if I change the component I get error saying:

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.

In Firebase real time database we call ref.off() to stop query.

Wondering how to do it in Firestore

componentDidMount() {
  Users.get().then(({ docs }) => {
    const users = docs.map(user => user.data());
      this.setState({ users });
  });
}

componentWillUnmount(){

}

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


如果有人仍在寻找答案,我找到了一种解决方法:

componentDidMount() {
  this.mounted = true;

  Users.get().then(({ docs }) => {
    const users = docs.map(user => user.data());
      if(this.mounted) this.setState({ users });
  });
}

componentWillUnmount(){
  this.mounted = false;
}

this.mounted当组件被卸载并且 setState 将不起作用时将为 false。


推荐阅读