【微信小程序】this指代与es6箭头函数处理 Cannot read property ‘data‘ of undefined

在微信小程序的onLoad函数中,通过wx.request获取数据并尝试赋值给data.list时出现TypeError,原因是回调函数内的this不再指向当前对象。解决方法包括:1) 使用变量that保存this的引用,然后用that.data.list赋值;2) 使用ES6的箭头函数,保持this指向。这两种方式都能有效解决this的作用域问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在微信小程序开发过程中,肯定会遇到过这个错误吧
VM447 WAService.js:2 TypeError: Cannot read property ‘data’ of undefined
在这里插入图片描述
这里遇到的就是this指代问题,可以看下面的例子

  /**
   * 页面的初始数据
   */
  data: {
    list:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.request({
      url: 'https://***/***/shop/goods/list',
      success:function(res){
        this.data.list = res.data
      }
    })
  },

通过wx.request请求列表,得到的结果赋值给data中的list
这时就回报错VM447 WAService.js:2 TypeError: Cannot read property ‘data’ of undefined
因为this的作用域发生了变化,在网络请求的回调函数中是访问不到data中的变量的。

解决方法1:使用this指代,将this保存到变量that中,在需要用this的地方使用that.data.list

  onLoad: function (options) {
    let that = this
    wx.request({
      url: 'https://***/***/shop/goods/list',
      success:function(res){
        that.data.list = res.data
      }
    })
  },

解决方法2:使用es6的箭头函数

  onLoad: function (options) {
    wx.request({
      url: 'https://***/***/shop/goods/list',
      success:(res)=>{
        this.data.list = res.data
      }
    })
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值