reactjs 错误“无效的括号赋值模式”背景信息

vfh0ocws  于 2023-04-20  发布在  React
关注(0)|答案(2)|浏览(151)

在我的React项目中,我得到了这个错误:

SyntaxError: ... Invalid parenthesized assignment pattern
const add = (a, b) = { return a + b; };
             ^

我确实理解错误,但我很惊讶我找不到任何关于它的信息

  • 它是从哪里来的?
  • 它在哪里被记录?

我想知道的是
我确实理解这里的问题 (箭头函数中缺少'〉'),但我想知道(1)这个错误到底来自哪里(不是浏览器?),以及(2)我可以在哪里找到有关它的信息。
错误消息显然将其解释为错误的赋值,而不是错误的箭头函数:

const add = (a, b) = { return a + b; };
// error ----^
// actually wrong --^

它显然不是来自哪里:

如果我在NodeJs CLI中编写相同的语句,则会得到:

const add = (a,b) = { return ''; }
            ^^^^^
ReferenceError: Invalid left-hand side in assignment

Firefox控制台

SyntaxError: invalid assignment left-hand side

请注意,我正在使用Firefox进行开发,但开发期间的错误消息与我在Firefox控制台中尝试相同操作时的错误消息不同(Invalid parenthesized assignment patternSyntaxError: invalid assignment left-hand side

xt0899hw

xt0899hw1#

由于使用的是ES6箭头函数,因此必须定义**=〉**

const add = (a, b) = { return a + b; }; // here you missed arrow for function **=>**

const add = (a, b) **=>** { return a + b; }; //modified by adding **=>**
7uzetpgm

7uzetpgm2#

错误消息来自Babel parser
该文本在babel / packages / babel-parser / src / parse-error / standard-errors.ts中定义:

InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",

文档

这些类型的错误 (显然) 没有在用户级别上记录,但在babel / packages / babel-parser / src / util / expression-scope.ts的源代码中有一些解释:
第32行:

- MaybeArrowParameterDeclaration
  A scope that represents ambiguous arrow head e.g. `(x)`. Errors will be recorded
  alongside parent scopes and thrown when `ExpressionScopeHandler#validateAsPattern`
  is called.

第164行:

* A parenthesized identifier (or type assertion) in LHS can be ambiguous because the assignment
* can be transformed to an assignable later, but not vice versa:
* For example, in `([(a) = []] = []) => {}`, we think `(a) = []` is an LHS in `[(a) = []]`,
* an LHS within `[(a) = []] = []`. However the LHS chain is then transformed by toAssignable,
* and we should throw assignment `(a)`, which is only valid in LHS. Hence we record the
* location of parenthesized `(a)` to current scope if it is one of MaybeArrowParameterDeclaration
* and MaybeAsyncArrowParameterDeclaration

相关问题