0

我正在尝试从 GET 请求(这是一个对象数组)中获取响应,并将其状态设置为数组“模板”,以便以后可以使用 this.state.templates 访问它,如下所示:

  fetch('https://tiy-warmup.herokuapp.com/api/templates?token=' + 
  token)
  .then(response => response.json())
  .then(response => this.setState({templates: response}))
  // .then(response => console.log(response))

当我将 setState 行注释掉并且只在控制台记录响应时,我得到了正确的数组,所以我知道我的 fetch 是好的。但是,当我尝试运行 setState 行时,出现此错误:

Possible Unhandled Promise Rejection (id: 0):
_this2.setState is not a function

解决此错误并能够在渲染中使用 this.state.templates 的解决方案是什么?

4

3 回答 3

0

无论您在何处使用此 fetch,都可以绑定该函数或更改为箭头函数。this未绑定到组件,因此this.setState引发错误。未处理的承诺拒绝错误正在显示,因为您没有设置 catch 语句来处理错误。

于 2017-04-18T23:46:06.297 回答
0

_this2.setState is not a function,通常,您的 this 不是您的组件的引用,启动您的调试器并仔细检查this引用的内容。我猜你可能会使用bindorconst self = this来解决这个问题。

看看这篇文章可能会对你有所帮助,https://www.sitepoint.com/bind-javascripts-this-keyword-react/

于 2017-04-19T00:49:15.897 回答
-1

可能的未处理承诺拒绝

发生此错误是因为您没有兑现catch您的承诺

.catch(error  => {
  console.log('There has been a problem with your fetch operation: '+ error.message);
});
于 2017-04-18T23:36:04.260 回答