[Vue warn]: "TypeError: Cannot read property 'type' of undefined?"

[Vue warn]: "TypeError: Cannot read property 'type' of undefined?"

有人可以帮我理解下面代码的行为吗?:

wrapperProperties () {
  let properties = this.getToValueOf('wrapper', {})
  [properties['type'], properties['message']] = this.defineValidationState()
  return properties
}

我收到以下警告:

[Vue warn]: Error in render function: "TypeError: Cannot read property 'type' of undefined"

当我在 let 关键字和解构赋值之间添加任何变量时,代码成功完成:

wrapperProperties () {
  let properties = this.getToValueOf('wrapper', {}), mysteriousVar
  [properties['type'], properties['message']] = this.defineValidationState()
  return properties
}

为什么会这样?

问题是这样的:

let properties = this.getToValueOf('wrapper', {})
[properties['type'], properties['message']]

解释为:

let properties = this.getToValueOf('wrapper', {})[properties['type'], properties['message']]

因此,它不是解构,而是被解释为使用 [] 语法的 属性 访问。

您应该在每个语句的末尾插入分号,或者您应该真正阅读并理解 standard.js 编码标准。根据 standard.js,您 必须 在以 {[.

开头的每一行的开头放置一个分号

我个人更喜欢经典的 "Douglas Crockford" 风格,所以我会在每个语句的末尾添加一个分号。但无论哪种方式都有效:

"Crockford" 风格:

wrapperProperties () {
  let properties = this.getToValueOf('wrapper', {});
  [properties['type'], properties['message']] = this.defineValidationState();
  return properties;
}

Standard.js 风格:

wrapperProperties () {
  let properties = this.getToValueOf('wrapper', {})
  ;[properties['type'], properties['message']] = this.defineValidationState()
  return properties
}