开发者问题收集

为什么我得到无法设置未定义的属性

2019-12-02
6190

我正在使用 nuxt js axios 开展小型项目,我尝试将响应数据放入我的 formFields 对象中,但我在控制台中收到未定义的错误消息,因为我已经在数据中声明了 formFields ,如您所见:

这是我的代码:

editCustomers (customerId, submit = false) {
  this.editMode = true
  this.customerId = customerId
  if (submit === 1) {
    // this.$Progress.start()
    this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {
      this.validation(data)
      // another form validation again using the helper
      this.refresh = true
    })
    // this.$Progress.finish()
  } else {
    this.$axios.$get('mydomain.com' + customerId).then(function (data) {
      this.formFields = data.customers[0]
    })
  }
}

我的数据变量:

data () {
return {
  laravelData: {},
  formFields: {},
  search: null,
  editMode: true,
  customerId: null,
  refresh: false
}
 }

如您所见,我已经声明了数据,但是当我执行 this.formFields = data.customers[0] 时,我收到此错误消息:

Uncaught (in promise) TypeError: Cannot set property 'formFields' of undefined
2个回答

只需将此部分更改为:

this.$axios.$get('mydomain.com' + customerId).then(function (data) {
  this.formFields = data.customers[0]
})

至此:

this.$axios.$get('mydomain.com' + customerId).then((data) => {
  // Now you can access your class instance
  this.formFields = data.customers[0]
})
Freeky
2019-12-02

在 JavaScript 中, this 指的是当前作用域的当前目标,当使用 function 关键字声明函数时, this 指的是调用该函数的对象。

您编写代码的方式, this 不再引用 Vue 实例, this 引用 undefined (因为回调可能是在没有 this 参数的情况下调用的),请尝试在函数外部捕获 this 并将其封闭在闭包中:

editCustomers (customerId, submit = false) {
  this.editMode = true
  this.customerId = customerId
  const vm = this; // vm = this = Vue instance
  if (submit === 1) {
    // this.$Progress.start()

    this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {
      // vm = Vue instance; this = undefined
      vm.validation(data)
      // another form validation again using the helper
      vm.refresh = true
    })
    // this.$Progress.finish()
  } else {
    this.$axios.$get('mydomain.com' + customerId).then(function (data) {
      // vm = Vue instance; this = undefined
      vm.formFields = data.customers[0]
    })
  }
}

ETA: 为了更好地理解这一点:

function myName() { return this.name};
var obj = {name:'test'};
var objName = myName.bind(obj); // a new function where the `this` arg is bound to `obj`
var text = objName(); // text === 'test'
console.log(text);
gabriel.hayes
2019-12-02