可能未处理的承诺拒绝.无法读取未定义的属性 [英] Possible Unhandled Promise Rejection. Cannot read property of undefined

查看:51
本文介绍了可能未处理的承诺拒绝.无法读取未定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是函数式 Javascript 和 promise 的新手.下面的代码很好用,直到我取消注释 this.writeDataToRealm(data.data).然后我得到这个错误:

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:

可能的未处理的承诺拒绝.无法读取未定义的属性writeDataToRealm"

Possible Unhandled Promise Rejection. Cannot read property 'writeDataToRealm' of undefined

如何将数据发送到函数进行进一步处理?

How can I send the data out to a function for further processing?

...
 fetch(url, {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    Authorization: "Bearer " + token
  },
  }).then(function(response) {
    if (response.status !== 200) {
      throw Error(response.statusText);
    } else {
        return response.json().then(function(data) {
          console.log(data);
          return data.data;
        })
      }
    }).then(data => {
      this.writeDataToRealm(data.data)
    }, err => {
      console.log('Fetch Error: ', err);
    });

   }

   writeDataToRealm(data) {
    console.log(data[0]);
    realm.write(() => {
      realm.create('Student', {id: data[0].kp_ID, bb_first_name: data[0].kp_ID});
    });
  }

推荐答案

未处理的拒绝 是因为你忘记了 return 来自 then<的内部承诺/code> 回调,这会导致异常不会冒泡到您的 catch 处理程序:

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;
    })
  }
});

<小时>

Cannot read property 'writeDataToRealm' of undefined 的问题是由 this 不是您期望的实例引起的 - 请参阅 如何在回调中访问正确的this/上下文?.最简单的解决方案是为回调使用箭头函数.


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);
});

这篇关于可能未处理的承诺拒绝.无法读取未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆