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

React定时器组件componentDidMount报Expected an assignment or function call错误

错误原因

你遇到的报错是ESLint的no-unused-expressions规则触发的,根源出在componentDidMount的写法上:

  • 类组件的生命周期函数体属于普通JS逻辑,不需要像JSX那样额外套花括号,你多写的两层嵌套大括号属于冗余语法
  • 单独使用三元表达式作为独立语句,没有将返回值赋值给变量或者作为函数入参使用,会被规则判定为无用表达式,直接抛出错误。

直接修复方案

把componentDidMount里的三元表达式替换成if分支语句即可,修改后的代码如下:

componentDidMount() {
  if (this.props.isRunning) {
    this.myInterval = setInterval(() => {
      this.tick()
    }, 1000)
  }
}

额外优化建议

当前代码还有两处潜在问题,可以同步调整:

  1. 缺少定时器清理逻辑,组件卸载后定时器还会继续执行,会引发内存泄漏,需要新增componentWillUnmount生命周期:
componentWillUnmount() {
  clearInterval(this.myInterval)
}
  1. 仅在组件挂载时判断isRunning,如果后续isRunning属性发生变化,定时器不会同步启停,可以新增componentDidUpdate生命周期处理动态切换:
componentDidUpdate(prevProps) {
  if (prevProps.isRunning === this.props.isRunning) return
  if (this.props.isRunning) {
    this.myInterval = setInterval(() => this.tick(), 1000)
  } else {
    clearInterval(this.myInterval)
  }
}

另外render函数内的变量声明不需要额外套花括号,删掉冗余的外层花括号代码可读性会更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:57:03