【问题标题】:Uncaught (in promise) TypeError: Cannot set property 'playerName' of undefined at eval未捕获(承诺中)TypeError:无法在评估时设置未定义的属性“playerName”
【发布时间】:2019-05-31 05:09:43
【问题描述】:

我正在尝试将 GET 请求中的 response.data.Response.displayName 分配给我的 playerName 属性,但是,我收到错误“Uncaught (in promise) TypeError: Cannot set property 'playerName' of undefined at eval”。我成功地在控制台记录了response.data.Reponse.displayName,所以里面有一个displayName。

为什么会出现这个错误?

export default {
  data: function() {
    return {
      playerName: ''
    }
  },
  methods: {

  },
  mounted() {
    axios.get('/User/GetBungieNetUserById/19964531/')
      .then(function(response) {
          this.playerName = response.data.Response.displayName
        console.log(response.data.Response.displayName)
      });
  }
}

【问题讨论】:

  • 使用(response) => { this.playerName = ...}。使用 function 关键字,您将失去原来的 this 上下文
  • 使用箭头函数代替:response=>{ this.playerName = /*..rest of code */}
  • 嗯,这种情况下一定要使用箭头函数吗?
  • 你可以在 axios 调用之前使用let that=this,并在回调中使用that 而不是this
  • @Bobimaru 不,你可以做到function(response){/* code */}.bind(this)

标签: javascript vue.js vuejs2 axios


【解决方案1】:

其他 cmets 和答案是正确的 - 使用箭头/lambda 函数而不只是 function 将起作用。但原因有细微差别。

Javascript 的this 概念定义明确,但并不总是您对其他语言的期望。 this 可以在您从回调之类的子功能执行时在一个范围块内更改。在您的情况下,then 中的函数不再理解 this,就像您直接在 mounted() 中运行相同的代码一样。

但是,您可以将函数绑定到(除其他目的外)附加一个无法更改的特定this。箭头函数隐式执行此操作,并将 this 绑定到 this 在创建箭头函数的上下文中。因此,这段代码:

axios.get('/User/GetBungieNetUserById/19964531/')
  .then((response) => {
      this.playerName = response.data.Response.displayName
    console.log(response.data.Response.displayName)
  });

正确理解this。它(大致上!)等同于以下内容:

axios.get('/User/GetBungieNetUserById/19964531/')
  .then((function(response) {
      this.playerName = response.data.Response.displayName
    console.log(response.data.Response.displayName)
  }).bind(this));

【讨论】:

  • 我正在做同样的事情,但我还是得到了错误。不过我使用了一个函数。
  • 看来我的问题是我没有在“mounted()”中做。我想通过单击按钮来完成。
【解决方案2】:

使用 lambda 函数(箭头函数)到达代码

export default {
  data: function() {
    return {
      playerName: ''
    }
  },
  methods: {

  },
  mounted() {
    axios.get('/User/GetBungieNetUserById/19964531/')
      .then((response) => {
          self.playerName = response.data.Response.displayName
        console.log(response.data.Response.displayName)
      });
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-11
    • 2019-05-16
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 2020-09-24
    • 1970-01-01
    相关资源
    最近更新 更多