小程序thirdScriptError, this.setData is not a function;

本文探讨了小程序开发中遇到的this指向问题,详细分析了前端控制台报错原因,并提供了将生命周期函数中的this传递到普通函数的解决方案。通过代码示例,展示了如何确保setData方法正确调用。

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

Problem

小程序开发过程中遇到this指向问题:

2018-07-31-ThisError.png

前端控制台报错:

thirdScriptError this.setData is not a function;

即:setData方法不存在。

Solution

将生命周期函数中的this传至普通函数;

通过以下代码,确定每个this分别指向哪里:

Page({
  data: {
    result: '',
  },

  onLoad: function(options) {
  },

  onReady: function() {
  },

  onShow: function() {
    let that = this;
    console.log('1: 生命周期函数中的this:', this);

    setInterval(function() {
      console.log('2: 定时函数中的this:', this);
      cronJob(that); // pass 'this' to normal method
    }, 10000);
  }
})

function cronJob(that) {
  console.log('3: 普通函数体中的this:', this);
  console.log('4: 普通函数体中的that:', that);
  wx.request({
    url: 'https://cn.bing.com/', // Just as an example
    method: 'GET',
    success: function(res) {
      let images = res.data.match(/\/az\/hprichbg\/rb\/(.){1,50}_1920x1080\.jpg/g); // regular expression
      let imageURL = `https://cn.bing.com${images[0]}`; // here must be https

      // that in wx.request
      this.setData({
        result: imageURL
      })
      console.log(that.data.result); // OK
    },
    fail: function(res) {
      console.log(res);
    }
  })
}

Result

2018-07-31-ThisResult.jpg


If you have any questions or any bugs are found, please feel free to contact me.

Your comments and suggestions are welcome!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Heartsuit

别说什么鼓励,这就是互联网乞讨

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值