问题描述
在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所说:
分配给声明为函数参数的变量可能会产生误导,并导致混乱的行为,因为修改函数参数也会使arguments对象发生变化。
“令人困惑的行为”应理解为例如奇怪的副作用。我记得在应用程序中造成了严重破坏,因为在函数内部,我对作为参数传递的数组进行了突变。该数组还被调用代码中的错误修改。这就是ESLint可以防止的事情!