微信小程序Cannot read property ‘setData‘ of null错误(已解决)

场景:在函数内使用了一个网络请求,返回的信息通过setData更新到页面


 sendClick: function(e) {
   // 将新发的消息添加到数组列表中
   msgList.push({
     speaker: 'customer',
     contentType: 'text',
     content: 'hello,world'
   })
   // 在此处可以直接通过this访问
   this.setData({
     msgList,
   });

   // 发送网络请求
   wx.request({
     method: "POST",
     url: "",
     data: {
       'speaker': 'customer',
       'contentType': 'text',
       'content': 'hello,world'
     },
     
     success:function(res){
       // 获取接收到的信息,然后添加到msgList数组中
       msgList.push({
         speaker: res.data['speaker'],
         contentType: res.data['contentType'],
         content: res.data['content']
       })
       // 更新到页面中
       this.setData({#这里报错
         msgList,
       });
     },
   })
 },

报错:

Cannot read property ‘setData’ of null;at pages/message/message
onReady function;at api request success callback function TypeError:
Cannot read property ‘setData’ of null

在这里插入图片描述

解决:

因为success是闭包,所以在这里使用的this指向的是闭包里面的,自然使用不了setData。解决办法就是在请求外面设置一个临时变量

sendClick: function(e) {
   // 将新发的消息添加到数组列表中
   msgList.push({
     speaker: 'customer',
     contentType: 'text',
     content: 'hello,world'
   })
   // 在此处可以直接通过this访问
   this.setData({
     msgList,
   });
   
   //将this对象复制到临时变量that
   var that = this;
	
   // 发送网络请求
   wx.request({
     method: "POST",
     url: "",
     data: {
       'speaker': 'customer',
       'contentType': 'text',
       'content': 'hello,world'
     },
     
     success:function(res){
       // 获取接收到的信息,然后添加到msgList数组中
       msgList.push({
         speaker: res.data['speaker'],
         contentType: res.data['contentType'],
         content: res.data['content']
       })
       // 此时that指向的就是上一层的this对象
       that.setData({
         msgList,
       });
     },
   })
 },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值