module.exports = async (ctx) => {
const reqUrl = ctx.request.header.referer;
const urlParam = url2param(reqUrl);
const offset = (urlParam.page - 1) * urlParam.pageSize;
try {
// 获取数据库数据
const data = await User.findAndCountAll({
attributes: [
'username',
'realname',
'phone',
'roleType',
'hasActive',
'createdAt'
],
offset,
limit: +urlParam.pageSize
});
// 将数据返回给前端
ctx.body = {data}; //eslint报错 require-atomic-updates
} catch (e) {
ctx.body = {...e}; //eslint报错 require-atomic-updates
}
};
前端返回数据无误,但是
eslint报错信息:
Possible race condition: ctx.body
might be reassigned based on an outdated value of ctx.body
.
没弄明白为什么,不知问题出在哪.
正好我也遇到这个问题了。其实官方文档的例子也是说明了问题:
这里面有多个异步操作同时进行,而顺序是不确定的,totalLength的值可能会发生不准确的赋值改变,导致结果不正确,后面也有提供解决办法。
我简单总结下,如果有多个异步方法,赋值给同一个变量,那这里面存在很多不确定性,可能发生错误。
而你的例子中只有一个await进行查询,其实是可以忽略这个错误的。直接在eslintrc配置中的
rule
添加"require-atomic-updates": "off",
来关闭提示。还是提醒一下:
这种就一定要小心了!