【问题标题】:Why can't I access 'this' scope in async method in vue js? [duplicate]为什么我不能在 vue js 的异步方法中访问 \'this\' 作用域? [复制]
【发布时间】:2023-01-23 21:45:42
【问题描述】:
async sendPostMessageForExit() {
      try {
        this.$mNprogress.show();

        await this.$store.dispatch(user/logout");

        this.$mNprogress.hide();
        this.postMessageExit();
      } catch (error) {
        handleGeneralError(error);
        this.$mNprogress.hide();
        this.postMessageExit();
      }
    },

让自己=这个;当我这样做时我可以访问它,但我想知道为什么我不能直接访问它。

【问题讨论】:

  • 那么你可以访问它
  • 可能是由于如何调用sendPostMessageForExit?请分享minimal reproducible example,因为当前示例未显示问题

标签: javascript vue.js vuejs2


【解决方案1】:

因为'this'没有绑定到函数。 像这样定义的函数具有动态作用域,这意味着它取决于您如何以及在何处称呼它。我对 Vue 不是很熟悉,但我想如果你从视图中调用这个函数,它的“this”将引用那个范围,而不是这个函数所属的类。

解决方案:

  1. 尝试改用箭头函数,它将具有词法作用域,即当您定义功能。 例如sendPostMessageForExit = async () => {...

  2. this 绑定到类构造函数中的函数(即 sendPostMessageForExit = sendPostMessageForExit.bind(this)

  3. 像你一样使用const self = this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-31
    • 2016-03-16
    • 2018-06-13
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    相关资源
    最近更新 更多