简体   繁体   中英

Possible unhandled promise rejection in react-native

I'm using following code which produce "Possible unhandled promise rejection":

constructor(props){
    super(props)

    DatabaseHandler.getInstance().getItems(function (items) {
            console.log(items)//successfully print data
            this.setState({inventoryArray: items}).bind(this)//causing error
        })
}

Though, following code runs successfully and prints response in log:

constructor(props){
        super(props)
        DatabaseHandler.getInstance().getItems(function (items) {
            console.log(items)//Successfully print data
        })
    }

How to resolve this error?

Typically, its a bad idea to make asynchronous calls in the constructor of the component. Instead, I would recommend that you make these calls from the componentDidMount as follows

class MyComponent extends React.Component {
  componentDidMount() {
    DatabaseHandler.getInstance().getItems(function (items) {
        console.log(items)//Successfully print data
        this.setState({ inventoryArray: items });
    });
  }
}

More about how to use the constructor in the official React docs

You could also remove bind and use arrow function so this keeps the context in your component.

constructor(props) {
  super(props)

  DatabaseHandler.getInstance().getItems((items) => {
    console.log(items)//successfully print data
    this.setState({inventoryArray: items})
  })
}

Also, your .bind(this) is in the wrong place. It should be placed in the outer } (where you close function )

constructor(props) {
  super(props)

  DatabaseHandler.getInstance().getItems(function (items) {
    console.log(items)
    this.setState({inventoryArray: items})
  }.bind(this)) // bind should come here
}

Making api requests in the constructor is a bad pattern though. ReactJS Docs mentions that componentDidMount is the recommended place to do so.

class YourComponent extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      inventoryArray: [],
    }
  }

  componentDidMount() {
    DatabaseHandler.getInstance().getItems((items) => {
      console.log(items)//successfully print data
      this.setState({inventoryArray: items})
    })
  }
}

Making following changes solved this issue:

 constructor(props) {
        super(props)
        this.onGetInventories = this.onGetInventories.bind(this)

        //Loading inventory list from server
        DatabaseHandler.getInstance().getItems(this.onGetInventories)
    }


    onGetInventories(items) {
        console.log(items)
        this.setState({inventoryArray: items})//Works
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM