javascript - 如何解决函数中的无参数重新分配错误

标签 javascript node.js eslint

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

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

最佳答案

你可以替换:

x.preferredContact = x.preferredContactHours;
return x;

有了这个:

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

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

现在,详细说明一下。作为rule's documentation说:

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.

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

关于javascript - 如何解决函数中的无参数重新分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64017725/

相关文章:

node.js - 我无法通过 "create-react-app"创建 React 应用程序

node.js - 如何等待mongodb获取值然后通过函数返回它

typescript - 对于使用 Prettier 的 .css 文件,SyntaxError : Unexpected token, 预期为 ";"

javascript - Node.js 中的回调函数

javascript - Web语音API语法

javascript - 如果小于 Max,则通过消除最少的用户将该值除以其他值

javascript - JQuery/Javascript 基于单选框在表格中设置输入框

mysql - sequelize.js orm :Unique email validation for mysql not working

javascript - Vue组件脚本缩进规则冲突

javascript - 如果不在 switch case 中声明 block 范围,是否会导致内存泄漏? (ESLint 无案例声明)