Possible Unhandled Promise Rejection. Cannot read property of undefined

后端 未结 1 1347
南旧
南旧 2021-01-27 16:35

I am new to functional Javascript and promises. The code bellow works great until I uncomment this.writeDataToRealm(data.data). Then I get this error:

Pos

相关标签:
1条回答
  • 2021-01-27 17:12

    The unhandled rejection is because you forgot to return the inner promise from the then callback, which causes an exception not to bubble to your catch handler:

    .then(function(response) {
      if (response.status !== 200) {
        console.log('Error Status Code: ' + response.status);
        // you might want to `throw` here
      } else {
        return response.json().then(function(data) {
          console.log(data);
          return data.data;
        })
      }
    });
    

    The problem with Cannot read property 'writeDataToRealm' of undefined is caused by this not being the instance you expected - see How to access the correct this / context inside a callback?. The simplest solution would be using an arrow function for the callback.

    …
    .then(data => {
      this.writeDataToRealm(data)
    }, err => {
      console.log('Fetch Error: ', err);
    });
    
    0 讨论(0)
提交回复
热议问题