【问题标题】:Possible Unhandled Promise Rejection. Cannot read property of undefined可能的未处理承诺拒绝。无法读取未定义的属性
【发布时间】:2019-06-04 23:26:45
【问题描述】:

我是功能性 Javascript 和 Promise 的新手。在我取消注释 this.writeDataToRealm(data.data) 之前,下面的代码效果很好。然后我得到这个错误:

可能的未处理承诺拒绝。无法读取未定义的属性“writeDataToRealm”

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

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

【问题讨论】:

    标签: javascript promise


    【解决方案1】:

    unhandled rejection 是因为您忘记了 return 来自 then 回调的内部承诺,这导致异常不会冒泡到您的 catch 处理程序:

    .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 不是您期望的实例引起的 - 请参阅How to access the correct this / context inside a callback?。最简单的解决方案是使用箭头函数进行回调。

    …
    .then(data => {
      this.writeDataToRealm(data)
    }, err => {
      console.log('Fetch Error: ', err);
    });
    

    【讨论】:

    • 我编辑了我的原始代码以反映您建议的更改。但是,我仍然收到相同的错误:可能的未处理承诺拒绝(id:12):无法读取未定义类型错误的属性“0”:无法读取 Database.writeDataToRealm 中未定义的属性“0”(/app/classes/Database. map?platform=ios&runModule=false&entryModuleOnly=true&hot=true:89:23) 在 eval (/app/classes/Database.map?
    • 这是一个不同的错误,因为现在它成功调用了writeDataToRealm 方法。我想我是用一个 .data 属性访问权限来调用它,不过
    • 谢谢,但我不确定你所说的“我猜我是用一个 .data 属性访问权限来调用它”是什么意思。我将如何解决这个问题?
    • @AdamG 我的意思是this
    • 啊,明白了!感谢您的帮助,现在效果很好!
    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 2017-05-29
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多