首页 > 解决方案 > 如何解决函数中的 no-param-reassign 错误

问题描述

在 Node/JS 函数中,我得到 ESLintno-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;
      });
  }

错误具体在这里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;
});

标签: javascriptnode.jseslint

解决方案


您可以更换:

x.preferredContact = x.preferredContactHours;
return x;

有了这个:

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

这样您就可以返回一个新对象,而不是修改函数的参数。

现在,详细说明一下。正如规则的文档所说:

对声明为函数参数的变量赋值可能会产生误导并导致混淆行为,因为修改函数参数也会改变 arguments 对象。

“令人困惑的行为”应理解为例如奇怪的副作用。我记得在一个应用程序中造成了严重破坏,因为在一个函数内部,我改变了一个作为参数传递的数组。调用代码中的数组也发生了变异,这是bad。这就是 ESLint 有助于防止的事情!


推荐阅读