ESLint警告ES6一致返回规则

16 ecmascript-6 eslint

我得到一个ESLint警告:

期望返回一个值艺术箭头函数的结束(一致返回)

errors.details.forEach((error) => {
  const errorExists = find(errObj, (item) => {  // <== ESLint warning
    if (item && item.field === error.path && item.location === location) {
      item.messages.push(error.message);
      item.types.push(error.type);
      return item;
    }
  });
  if (!errorExists) {
    errObj.push({
      field: error.path,
      location: error.location,
      messages: [error.message],
      types: [error.type]
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

但是,如果我插入一个返回

  const errorExists = find(errObj, (item) => {    // <== ESLint warning
    if (item && item.field === error.path && item.location === location) {
      item.messages.push(error.message);
      item.types.push(error.type);
      return item;
    }
    return;   // <== inserted return
  });
Run Code Online (Sandbox Code Playgroud)

然后在这一行没有更多的警告,但是我在插入的返回上得到2个警告......

箭头函数期望返回值(一致返回)不必要的返回语句(无用无效返回)我没有看到如何正确解决这个问题..任何反馈欢迎

Jay*_*ayK 20

http://eslint.org/docs/rules/consistent-return说:

此规则要求return语句始终或从不指定值.

如果不满足if条件,则箭头函数将终止而不会遇到违反此规则的return语句.您的第二个版本违反了此规则,因为您的第二个返回没有指定值,与第一个返回相反.第二个警告告诉您额外的return语句是多余的.

为了使linter快乐,如果条件不满足,你可能应该考虑从箭头函数正确返回什么.我不知道你的find函数究竟做了什么,但如果它的行为类似于Array.prototype.find,你可能希望在箭头函数的末尾返回false.如果在这种情况下需要返回undefined,则同一页面中的此段落适用:

何时不使用它

如果要根据代码分支允许函数具有不同的返回行为,则可以安全地禁用此规则.

编辑:我以前写过看看该选项treatUndefinedAsUnspecified,但看起来如果您需要在其中一个分支中返回undefined,则任何设置都无济于事.

  • 一种方法是在您的 .eslintrc.json (或 eslint 配置文件)上添加其“rules”主属性: ..."rules": { "consistency-return": "off""}... // You可以将其设置为“关闭”、“警告”或“错误” (2认同)
  • 上面的内容将禁用所有内容的规则。要禁用特定文件,请在文件顶部添加注释“/* eslint-disable constreturn */”。使用 `// eslint-disable-line concent-return` 禁用一行。使用 `// eslint-disable-next-line concent-return` 禁用下一行。https://eslint.org/docs/user-guide/configuring#disabling-rules-with-inline-comments (2认同)

小智 9

返回正确插入,但应给出其值...

return false;
Run Code Online (Sandbox Code Playgroud)

是正确的价值