收藏
回答

为什么云函数后不可以使用this.show()?

回答关注问题邀请回答
收藏

3 个回答

  • 肖荣豪
    肖荣豪
    2022-05-09

    this指向问题,

    settimeout等定时器的this是指向 window 的

    使用 let that = this 就行

    2022-05-09
    有用 1
    回复 1
    • 飞
      发表于移动端
      2022-05-09
      多谢大佬指点
      2022-05-09
      回复
  • شەرەر
    شەرەر
    2022-05-09

    这是写法问题,如果函数写成如下:

    success: function(res) {}
    

    这时候函数里面的this已经指定为函数本身,而函数没有那些方法和事件。对于这个有几种解决方法。

    1.最外层定义一个变量并this赋值给他,函数里面直接用定义的变量即可。

    let that = this;
    wx.cloud.callFunction({
      success: function(res) {
        that.setData({});
      }
    });
    

    2. 对于this进行绑定。

    wx.cloud.callFunction({
      success: function(res) {
        this.setData({});
      }.bind(this)
    });
    

    3.写lambda表达式(匿名函数)写法。

    wx.cloud.callFunction({
      success: (res) => {
        this.setData({});
      }
    });
    
    2022-05-09
    有用 1
    回复 1
    • 飞
      发表于移动端
      2022-05-09
      多谢大佬指点
      2022-05-09
      回复
  • 铅笔Naruto
    铅笔Naruto
    2022-05-08

    在最外层加个let that=this,然后that.onShow()就可以了

    2022-05-08
    有用 1
    回复 2
    • 飞
      2022-05-08
      多谢了,不过我也好奇为什么有时候this不行设置为that又可以了
      2022-05-08
      回复
    • 铅笔Naruto
      铅笔Naruto
      2022-05-09回复
      因为像放到了settimeout里面了,在这个函数里this指向的是这个函数本身
      2022-05-09
      回复
登录 后发表内容