You need to enable JavaScript to run this app. 使用Webpack集成react-i18next时调用useTranslation出现无效Hook错误
优惠活动
大模型
产品
解决方案
定价
更多

使用Webpack集成react-i18next时调用useTranslation出现无效Hook错误

问题修复方案

  • 修复webpack配置拼写错误
    你的webpack.config.js中babel-loader的排除规则拼写错误,将exclude: /nodeModules/修改为exclude: /node_modules/即可。拼写错误导致babel没有正确排除node_modules目录,容易生成多个React实例,触发Hook调用规则校验失败。
    修正后的对应规则代码:
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: {
        loader: "babel-loader"
      }
    }
    
  • 补充i18next初始化配置
    在i18next.js的init配置中添加关闭Suspense的配置,避免未包裹Suspense组件导致的异常:
    i18next
      .use(initReactI18next)
      .use(HttpApi)
      .init({
        backend: {
          loadPath: '/locales/{{lng}}/{{ns}}.json'
        },
        lng: "en_GB",
        supportedLngs: ["en_GB","cs_CZ"],
        react: {
          useSuspense: false
        }
    })
    
  • 检查入口文件引入逻辑
    确认项目入口文件(通常为src/index.js)顶部已引入你编写的i18next配置文件:
    import './i18next'
    
  • 清理依赖解决多副本问题
    如果修改上述配置后仍有报错,删除项目下的node_modules文件夹、package-lock.json或yarn.lock文件,重新执行npm install或yarn install安装依赖,解决多个React副本导致的Hook调用异常。

你将locales放在public目录的配置是正确的,CopyPlugin会正常把public下的多语言文件打包到dist目录,不需要调整这部分逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 14:06:05