在 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/