为何mongoose代码触发ESLint的Unexpected function expression报错?
prefer-arrow-callback报错问题 Hey there! Let's break down this ESLint error you're hitting with your Mongoose code.
问题根源
The Unexpected function expression. (prefer-arrow-callback) error comes directly from ESLint's prefer-arrow-callback rule. This rule is designed to encourage using arrow functions instead of traditional function expressions for callbacks, and here's why:
- Arrow functions don't bind their own
thisvalue — they inherit thethisfrom the surrounding scope, which avoids common bugs wherethispoints to something unexpected in callbacks. - They have a more concise syntax that makes your code cleaner and easier to read.
In your code, you're using a standard function() expression as the callback for kitty.save(), which violates this rule.
修复方案
The fix is straightforward: replace the traditional function with an arrow function. Here's how your code can be adjusted:
原代码
kitty.save(function (err) { if (err) { console.log('a'); } });
修改后的代码
kitty.save((err) => { if (err) { console.log('a'); } });
If you want to make it even more concise (since the callback only has one parameter), you can omit the parentheses around err:
kitty.save(err => { if (err) { console.log('a'); } });
临时禁用规则(不推荐)
If for some reason you need to keep the traditional function (e.g., if you rely on the callback's own this), you can disable the rule for that specific line with a comment:
// eslint-disable-next-line prefer-arrow-callback kitty.save(function (err) { if (err) { console.log('a'); } });
额外说明
Using arrow functions for Mongoose callbacks is generally a good practice because it keeps the this context consistent with your outer code (like if you're working inside a class method). You won't have to do tricks like const that = this or .bind(this) to access outer scope variables.
内容的提问来源于stack exchange,提问作者Saeed Heidarizarei

