简体   繁体   English

如何解决 function 中的无参数重新分配错误

[英]How to resolve no-param-reassign error in a function

In a Node/JS function, I'm getting ESLint no-param-reassign the code is for update a candidate as follow在 Node/JS function 中,我得到 ESLint no-param-reassign代码用于更新候选者,如下所示

update(candidate) {
    const { id } = candidate;
    if (!id) {
      throw new UserInputError('id is mandatory');
    }

    return this.tx(tableName)
      .returning(Object.values(columnsByProperties))
      .where('id', id)
      .update(prepareCandidate(candidate))
      .reduce((_, b) => camelcaseKeys(b), null)
      .then(x => {
        if (!x) {
          throw new UserInputError(`Candidate "id" with ${id} is not found`);
        }
        x.preferredContact = x.preferredContactHours;
        return x;
      });
  }

The error specifically is here Assignment to property of function parameter 'x'具体错误在这里Assignment to property of function parameter 'x'

.then(x => {
   if (!x) {
     throw new UserInputError(`Candidate "id" with ${id} is not found`);
     }
     x.preferredContact = x.preferredContactHours;
     return x;
});

You can replace:您可以替换:

x.preferredContact = x.preferredContactHours;
return x;

With this:有了这个:

return { ...x, preferredContact: x.preferredContactHours };

This way you return a new object instead of modifying the function's parameter.这样您就可以返回一个新的 object 而不是修改函数的参数。

Now, elaborating a bit.现在,详细说明一下。 As the rule's documentation says:正如规则的文档所说:

Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object.分配给声明为 function 参数的变量可能会产生误导并导致混淆行为,因为修改 function 参数也会使 arguments object 发生变异。

"Confusing behavior" is to be understood as, for example, odd side effects. “混淆行为”应理解为例如奇怪的副作用。 I remember wreaking havoc in an app because inside a function, I mutated an array that was passed as a parameter.我记得在一个应用程序中造成了严重破坏,因为在 function 中,我改变了一个作为参数传递的数组。 The array was also mutated in the calling code which was bad .该数组在调用代码中也发生了变异,这是错误的 That's the kind of thing ESLint helps prevent!这就是 ESLint 有助于防止的事情!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM