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

React运行时报TypeError: this.state.toLocaleTimeString is not a function如何解决

错误原因

React 类组件的 setState 默认执行对象浅合并逻辑:你传入的参数如果是对象,React 只会把这个对象的可枚举属性拆分后合并到原有 state 上,不会直接替换整个 state 对象。
你给 setState 传入的是 new Date() 这个 Date 类实例,React 会把 Date 实例的属性(比如年、月、日、时间戳等)拆分出来合并到原 state,最终 this.state 会变成一个普通的 JavaScript 对象,不再是 Date 实例,自然没有 toLocaleTimeString 方法,就触发了报错。
另外 React 官方也明确要求 state 应该是普通的 JavaScript 对象,不要直接存储类实例,避免出现这类不可预期的合并问题。

修复方案

推荐调整 state 结构,把日期存在 state 对象的单独字段中,符合 React 的设计规范:

class Clock extends Component {
  constructor(props) {
    super(props)
    // state声明为普通对象,日期存放在currentTime字段
    this.state = {
      currentTime: new Date()
    }
  }

  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000)
  }

  componentWillUnmount() {
    clearInterval(this.timerID)
  }

  tick() {
    // 传入对象,仅更新currentTime字段
    this.setState({
      currentTime: new Date()
    })
  }

  render() {
    return (
      <div>
        <h2>It is {this.state.currentTime.toLocaleTimeString()}.</h2>
      </div>
    )
  }
}

ReactDOM.render(<Clock />, document.getElementById('root'));

修改后 currentTime 字段始终是 Date 实例,调用 toLocaleTimeString 方法不会再触发报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:57:01