在微信小程序开发过程中,肯定会遇到过这个错误吧
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
      }
    })
  },
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐