开发者社区
社区提问意见反馈
开发者钉组织
扫描二维码
加入支付宝开发者钉组织
文档中心
凯发app官方网站的技术支持 & 案例 faq 
支付宝小程序
案例分析
sdk & demo下载
常见问题
常用工具
iot小程序
运维保障
小程序 > 支付宝小程序 > 常见问题 > cannot read property 'setdata' of undefined
贡献者
收藏
我的文档
设置
报错描述
在 api 异步回调函数中使用 this 调用 page 的变量和函数,报错 undefined。
例如:在 my.requset 成功回调函数 success 中 this.setdata({}) 赋值,直接报:uncaught typeerror: cannot read property 'setdata' of undefined

报错原因
this 指向改变导致,在异步回调函数中 this 不是指向页面 page,而是指向回调函数局部,所以 this 找不到 page 的变量或函数报错。
凯发app官方网站的解决方案
异步回调函数中使用 this,需要在外部重新定义一个 let that=this 然后使用 that.setdata({}) 进行数据的赋值。
javascript
复制代码
data: {
setvalue:"",
},
onready(e) { //重新定义thislet
that=this;
my.request({
url: 'https://httpbin.org/post',
method: 'post',
data: {
from: '支付宝',
production: 'alipayjsapi',
},
headers:{
'content-type':'application/json' //默认值
},
datatype: 'json',
success: function(res) {
my.alert({content: 'success'});
that.setdata({
setvalue:"重新定义this success"
})
},
fail: function(res) {
my.alert({content: 'fail'});
},
complete: function(res) {
my.hideloading();
my.alert({content: 'complete'});
}});
}
使用回调箭头函数写法,这样就不存在 this 指向问题,直接使用 this.setdata({}) 进行数据的赋值。
内容没有解决您的问题?您还可以前往 或 寻求帮助
凯发k8官方网娱乐官方 copyright © 2022 支付宝(杭州)信息技术有限公司  | icp证浙b2-20160559
该文档对你是否有帮助?
当前页面目录
网站地图