异常:thirdScriptError totalCost is not defined;at api request success callback function ReferenceError

异常提示

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赋给一个新的变量才可以了。

参考:
  1. 微信小程序Cannot read property ‘setData’ of null;
  2. 逍遥云天微信小程序开发——使用回调函数出现异常: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成功,获取数据失败");
        }
      }
    **********
    **********

以上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值