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) } }
额外优化建议
当前代码还有两处潜在问题,可以同步调整:
- 缺少定时器清理逻辑,组件卸载后定时器还会继续执行,会引发内存泄漏,需要新增
componentWillUnmount生命周期:
componentWillUnmount() { clearInterval(this.myInterval) }
- 仅在组件挂载时判断
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
相关产品推荐
相关产品推荐

