无法对未安装的组件执行 React 状态更新。 (Class 分量)

Can't perform a React state update on an unmounted component. (Class component)

问题

我正在用 React Native 编写应用程序,但无法修复此特定警告。我知道这是由发出数据请求引起的,但组件在请求完成之前卸载了。 但无法正常工作。这是我的代码,我也应用了下面的解决方案。

class PeopleScreen extends React.Component {

      constructor(props) {
        super(props);
        this.state = {
          listData : [ ]
        };
    
      }
  
      componentDidMount() {
        // Get list of people.
        AsyncStorage.getItem("people",
          function(inError, inPeople) {
            if (inPeople === null) {
              inPeople = [ ];
            } else {
              inPeople = JSON.parse(inPeople);
            }
            this.setState({ listData : inPeople });
          }.bind(this)
        );
    
      };
   
      render() { return (
      )

这是我应用的解决方案:

 class PeopleScreen extends React.Component {
    _isMounted = false;

      constructor(props) {

        super(props);

        this.state = {
          listData : [ ]
        };

      }

      componentDidMount() {
        this._isMounted = true;

        // Get list of people.
        AsyncStorage.getItem("people",
          function(inError, inPeople) {
            if (inPeople === null) {
              inPeople = [ ];
            } else {
              inPeople = JSON.parse(inPeople);
            }
            this.setState({ listData : inPeople });
          }.bind(this)
        );

      };

      componentWillUnmount() {
        this._isMounted = false;
      }

      render() { return ( 

      )

另外,看报错:

您需要用 if 语句包装 setState 以检查 _isMounted 值是否为真

if(this._isMounted) {
  this.setState({ listData : inPeople });
}

我感觉这里的异步代码可能有问题。您的回调看起来不错,从技术上讲应该可以,但我建议您尝试将回调重写为 Promise resolution

除此之外,您还可以通过以下方式改进代码,去除多余的 if/else,但这更像是一种审美偏好。

AsyncStorage.getItem('people').then(async (value) => {
  let inPeople = value ? JSON.parse(value) : [];
  this.setState({ listData : inPeople });
  // or even a one-liner: this.setState({ listData : value ? JSON.parse(value) : [] });
});