异常提示
VM789:1 thirdScriptError
totalCost is not defined;at api request success callback function
ReferenceError: totalCost is not defined
at success (http://127.0.0.1:12446/appservice/pages/home/home.js:92:25)
at Function.o.(anonymous function) (http://127.0.0.1:12446/appservice/__dev__/WAService.js:1:1296511)
at http://127.0.0.1:12446/appservice/__dev__/WAService.js:1:125690
at k (http://127.0.0.1:12446/appservice/__dev__/WAService.js:1:526119)
at i.<anonymous> (http://127.0.0.1:12446/appservice/__dev__/WAService.js:1:832038)
at i.emit (http://127.0.0.1:12446/appservice/__dev__/WAService.js:1:574350)
at Xi (http://127.0.0.1:12446/appservice/__dev__/WAService.js:1:832676)
at http://127.0.0.1:12446/appservice/__dev__/WAService.js:1:833896
at http://127.0.0.1:12446/appservice/__dev__/WAService.js:1:597101
at n (http://127.0.0.1:12446/appservice/__dev__/asdebug.js:1:3175)
出现场景及部分相关代码
getUserInfo: function (e) {
**********
**********
success:function(res){
if(res.data.message == "success"){
console.log("调用homeAction/getTotalCostAndCalories成功,且获取数据成功");
this.setData({
totalCost : res.data.totalCost,
calories : res.data.calories
})
}
if(res.data.message == "fail"){
console.log("调用homeAction/getTotalCostAndCalories成功,获取数据失败");
}
}
**********
**********
从后台(Java)向前台(微信小程序home.js)返回两个值(totalCost,calories )。
在将这两个值分别赋值给页面参数(totalCost,calories )的时候,出现如上错误。
分析原因
根据提示,应该是与回调函数callback 有关。
网上的说法:作用域问题——回调函数中的作用域已经脱离了调用函数了,因此需要在回调函数外边把this赋给一个新的变量才可以了。
参考:
- 微信小程序Cannot read property ‘setData’ of null;
- 逍遥云天微信小程序开发——使用回调函数出现异常:TypeError: Cannot read property ‘setData’ of undefined
解决方法
```javascript
getUserInfo: function (e) {
**var myThis = this;**
**********
**********
success:function(res){
if(res.data.message == "success"){
console.log("调用homeAction/getTotalCostAndCalories成功,且获取数据成功");
**myThis**.setData({
totalCost : res.data.totalCost,
calories : res.data.calories
})
}
if(res.data.message == "fail"){
console.log("调用homeAction/getTotalCostAndCalories成功,获取数据失败");
}
}
**********
**********