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

微信小程序 报错: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)
      }
    })

  },

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

猜你喜欢

转载自blog.csdn.net/qq_43263320/article/details/113706520