分享你我的心得.
共乘一片美好网络.

微信小程序报错:TypeError: Cannot read property ‘setData’ of undefined解决方法

在完成微信小程序的一个功能时,偶然间报了一个错误。
错误信息是:TypeError: Cannot read property ‘setData’ of undefined。

出错代码

每当我执行homework这个函数时,我发送一个request请求,将获取的数据存导本地的数组中。故我在sucess:function(res){}中使用了this.setData({})。

  homework: function () {
    if (this.data.homeworkpageFlag == false) {
      console.log(this)
      this.setData({
        homeworkpageFlag: true,
        saypageFlag: false,
        exampageFlag: false,
      })
    }
    wx.request({
      url: '某url hhhhh',
      data: {
        student_id: '某学号',
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res.data)
        this.setData({
          homeworkNoCompleteList: res.data.data.homeworkNoCompleteList
        })
      }
    })

  },


理想很美好,但是每次执行就会报上面的错误。

解决方案

  1. var that = this;
  2. ES6的箭头函数

方案一、var that = this;

添加 var that = this;并把sucess中的this.setData改成that.setData

homework: function () {
    if (this.data.homeworkpageFlag == false) {
      console.log(this)
      this.setData({
        homeworkpageFlag: true,
        saypageFlag: false,
        exampageFlag: false,
      })
    }
    //添加var that = this
    var that = this;
    wx.request({
      url: 'https://fanzaixuexi.applinzi.com/public/index.php/index/GetInformation/get_all_assignment',
      data: {
        student_id: '某学号',
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res.data)
        //改成了that.setData
        that.setData({
          homeworkNoCompleteList: res.data.data.homeworkNoCompleteList
        })
      }
    })
  },


成功解决问题。

方案二、ES6箭头函数;

  homework: function () {
    if (this.data.homeworkpageFlag == false) {
      console.log(this)
      this.setData({
        homeworkpageFlag: true,
        saypageFlag: false,
        exampageFlag: false,
      })
    }
    wx.request({
      url: '某url',
      data: {
        student_id: '某id',
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res)=> {
        console.log(res.data)
        // var that = this;
        this.setData({
           // 我要获取的数据
        })
        console.log(this.data.homeworkYesCompleteList.length)
      }
    })

  },

把 success:function(res){}改成 success:(res)=>{}
就可以大大方方地使用 this.setData了

赞(0)
未经允许不得转载:小叶白龙博客 » 微信小程序报错:TypeError: Cannot read property ‘setData’ of undefined解决方法
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址