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

Next.js 13.4客户端组件useEffect与State不更新问题求助

Next.js 13.4客户端组件useEffect不执行、状态不更新问题解决

问题现象

通过npx create-next-app@latest创建项目后,/app/components/目录下的Counter客户端组件出现异常:

  • 终端能打印The component is mounted,但浏览器控制台无useEffect日志输出
  • 点击按钮后count状态不更新
  • Edge/Chromium浏览器报错:
    Uncaught (in promise) Error: Cannot read properties of undefined (reading '_RUNTIME_')
        at wrappedSendMessageCallback (AEKXD7GI.js:920:22)
    

相关代码

Counter.tsx

'use client'

import { useEffect, useState } from 'react'

export default function Counter() {
  const [count, setCount] = useState(0)
  console.log('The component is mounted')
  useEffect(() => {
    console.log('This line should print in the browser console')
  }, [])
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  )
}

/app/page.tsx

import Counter from './components/Counter'

export default function Home() {
  return (
    <main>
      <Counter />
    </main>
  )
}

依赖版本

"dependencies": {
    "@types/node": "20.5.7",
    "@types/react": "18.2.21",
    "@types/react-dom": "18.2.7",
    "autoprefixer": "10.4.15",
    "eslint": "8.48.0",
    "eslint-config-next": "13.4.19",
    "next": "13.4.19",
    "postcss": "8.4.28",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "tailwindcss": "3.3.3",
    "typescript": "5.2.2"
  }

解决方案

  • 禁用浏览器扩展
    该_RUNTIME_错误大概率是浏览器扩展(如广告拦截、隐私保护类)干扰了Next.js的客户端运行时脚本。直接禁用所有扩展,重启浏览器后测试。

  • 清除缓存并重建项目

    1. 删除Next.js构建缓存和依赖缓存:
      rm -rf .next node_modules/.cache
      
    2. 重新安装依赖:
      npm install
      
    3. 启动开发服务器:
      npm run dev
      
    4. 浏览器端强制刷新(Ctrl+Shift+R),或打开开发者工具在Network标签勾选「Disable cache」后刷新页面。
  • 检查客户端组件指令和导入
    确认'use client'是Counter组件的第一行代码,前面不能有任何空行、注释或隐形字符。若编辑器可能插入了隐形字符,可重新输入该行指令。同时验证page.tsx中的组件导入路径是否正确。

  • 重置Next.js配置
    检查next.config.js,若存在自定义webpack配置或实验性特性,暂时注释这些配置,使用默认配置测试。13.4版本App Router已稳定,无需额外开启experimental.appDir。

  • 重新初始化项目验证
    创建一个全新的Next.js项目,仅添加Counter组件和修改page.tsx,测试是否能正常运行:

    npx create-next-app@latest test-app --typescript --tailwind --eslint
    cd test-app
    # 创建app/components/Counter.tsx并复制代码
    # 修改app/page.tsx导入Counter
    npm run dev
    

    若新项目正常,说明原项目存在配置或缓存损坏问题,可逐步迁移配置和代码到新项目。

内容的提问来源于stack exchange,提问作者7Codo - Ayoub

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:52:03