微信小程序 this.setData 提示:Cannot read property 'setData' of undefined
时间: 2024-06-08 17:11:08 浏览: 17
这个错误通常是因为在调用 `setData()` 方法时,`this` 对象未被正确绑定。请确保在调用 `setData()` 方法之前,`this` 对象已经被正确地绑定到当前组件实例。你可以使用箭头函数来确保 `this` 对象的正确绑定,例如:
```
// 正确的写法
getData() {
wx.request({
url: 'http://example.com',
success: (res) => {
this.setData({
data: res.data
})
}
})
}
```
如果你使用普通函数,你需要在函数内部保存 `this` 对象的引用,例如:
```
// 错误的写法
getData() {
wx.request({
url: 'http://example.com',
success: function(res) {
// 此处的 this 是 wx.request 的 this,而不是当前组件实例的 this
this.setData({
data: res.data
})
}
})
}
// 正确的写法
getData() {
var that = this;
wx.request({
url: 'http://example.com',
success: function(res) {
// 此处的 this 是 wx.request 的 this,而不是当前组件实例的 this
that.setData({
data: res.data
})
}
})
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)