使用for-in循环触发ESLint guard-for-in错误,无法提交至Git
解决ESLint guard-for-in报错的两种方案
方案一:修复代码符合规则要求
ESLint的guard-for-in规则要求for-in循环必须过滤原型链上的继承属性,避免意外遍历到非预期的属性。你可以在循环内添加hasOwnProperty检查,确保只处理对象自身的属性:
toJSON: function () { let json = _.clone(this.attributes); // add in the calculated fields for event model if (typeof this.calFields === 'object') { for (var comp in this.calFields) { // 仅处理对象自身的属性,过滤原型链属性 if (this.calFields.hasOwnProperty(comp)) { var v2; if (this._computedCache && this._computedCache[comp]) { v2 = this._computedCache[comp]; } else { v2 = this.calFields[comp].apply(this); } json[comp] = v2; } } } return json; }
方案二:正确禁用该规则(仅当确认无需过滤时)
你之前的禁用注释位置错误,导致ESLint未识别到指令。需要将禁用注释放在for-in语句的紧邻位置:
方式1:行内注释(作用于当前行)
for (var comp in this.calFields) { // eslint-disable-line guard-for-in
方式2:前置单行注释(作用于下一行)
// eslint-disable-next-line guard-for-in for (var comp in this.calFields) {
调整后,ESLint会忽略该循环的guard-for-in检查,允许提交代码。
内容的提问来源于stack exchange,提问作者kez
相关产品推荐
相关产品推荐

