You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React箭头函数Unexpected block statement报错修复方法

问题描述

现有如下数组:

const reportOptions = [
  {
    id: 1,
    title: 'Report',
  },
  {
    id: 2,
    title: 'Report 2',
  },
  {
    id: 3,
    title: 'Report 3',
  },
]

使用以下代码创建React状态时:

const [isReportsDownloading, setIsReportsDownloading] = useState(
  reportOptions.map(opt => {
    return { ...opt, isDownloading: false }
  })
)

触发ESLint报错:

Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the =>

报错原因

该报错来自ESLint的arrow-body-style校验规则:当箭头函数的函数体仅包含一行return语句时,规则要求使用隐式返回的简洁写法,不需要额外包裹块级大括号、书写显式return。
注意:由于要返回的是对象字面量,隐式返回时必须用小括号包裹对象,否则JS引擎会把对象的大括号识别为函数体的起始标记,触发语法错误。

修复方法

直接将map的回调函数改为隐式返回写法即可,修改后代码如下:

const [isReportsDownloading, setIsReportsDownloading] = useState(
  reportOptions.map(opt => ({ ...opt, isDownloading: false }))
)
  • 移除箭头函数后包裹代码块的大括号,以及块内的return关键字
  • 待返回的对象外层包裹小括号,避免语法解析冲突

如果需要保留块级写法与显式return,也可以在ESLint配置中关闭arrow-body-style规则,但该简洁写法是JavaScript与React项目的通用编码规范,优先推荐使用。

内容的提问来源于stack exchange,提问作者CCCC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 18:06:26