【问题标题】:Uncaught (in promise) TypeError: _this is not a functionUncaught (in promise) TypeError: _this is not a function
【发布时间】:2020-06-02 17:06:30
【问题描述】:

我正在做一个简单的 axios 调用,如果成功,请举杯。吐司功能也在那里并且工作正常,因为我在 100 个不同的地方使用它。

控制台日志显示{data: "Payment Successful", status: 200, statusText: "OK", headers: {…}, config: {…}, …} 表示调用正常,只是this 不是...

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}

错误: Uncaught (in promise) TypeError: _this.toast is not a function

过去 2 天我在互联网上搜索,但找不到任何东西。有些人建议使用 async/await 但也没有运气。与往常一样,堆栈溢出是我最后的手段。如果您需要更多信息,请在下面添加评论。

谢谢。

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案1】:

    将您的处理程序切换到箭头函数以避免更改范围:

    this.razorPayOptions = {
        'key': process.env.MIX_RAZORPAY_KEY,
        'name': process.env.MIX_APP_NAME,
        'description': 'Details ...',
        'handler': (request) => {
            axios.post('/api/transaction/complete', request)
                .then(response => {
                    console.log(response);
                    this.toast(response.data, response.status); // this is where the error occurs
                });
        }
    }
    

    查看此answer 了解更多上下文

    【讨论】:

      【解决方案2】:

      您可以切换到箭头函数,或在定义回调之前捕获this

      this.razorPayOptions = {
          'key': process.env.MIX_RAZORPAY_KEY,
          'name': process.env.MIX_APP_NAME,
          'description': 'Details ...',
          'handler': function (request) {
              const that = this;
              axios.post('/api/transaction/complete', request)
                  .then(response => {
                      console.log(response);
                      that.toast(response.data, response.status); // this is where the error occurs
                  });
          }
      }
      

      【讨论】:

      • 你也可以在hander .then{}.bind(this))的末尾加上.bind(this);
      【解决方案3】:

      问题是您误读了范围。要解决您的问题,请将函数更改为箭头函数。

      this.razorPayOptions = {
      'key': process.env.MIX_RAZORPAY_KEY,
      'name': process.env.MIX_APP_NAME,
      'description': 'Details ...',
      'handler': (request) => {
          axios.post('/api/transaction/complete', request)
              .then(response => {
                  console.log(response);
                  this.toast(response.data, response.status); // this is where the error occurs
              });
         }
      }
      

      你能阅读这篇文章https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc

      【讨论】: