我试图从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的解决方案是什么?
发布于 2017-04-18 23:46:06
无论您在何处使用此fetch,都可以绑定该函数或更改为箭头函数。this没有绑定到组件,因此this.setState抛出了一个错误。未处理的允诺拒绝错误正在显示,因为您没有设置catch语句来处理错误。
发布于 2017-04-19 00:49:15
_this2.setState is not a function,通常,您的这不是您的组件的参考,启动您的调试器,并仔细检查什么是this ref。我想您可以使用bind或const self = this来解决这个问题。
看看这篇文章也许对你有帮助,https://www.sitepoint.com/bind-javascripts-this-keyword-react/
发布于 2017-04-18 23:36:04
可能未处理的拒绝承诺
发生此错误是因为您没有按照您的承诺实现catch
.catch(error => {
console.log('There has been a problem with your fetch operation: '+ error.message);
});https://stackoverflow.com/questions/43483666
复制相似问题