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

使用i18next及相关中间件时出现TypeError: Cannot read property 'use' of undefined错误的原因及解决方法

问题原因分析与解决方法

这个错误的核心原因是你对i18next和i18next-http-backend的导入方式不正确,导致Backend变量为undefined,进而无法调用.use()方法。

为什么会出现这个问题?

你使用的i18next-http-backend@1.4.0和i18next@21.6.14版本,它们的CommonJS导出是直接暴露模块本身,而不是通过.default属性。你在导入时额外添加了.default,相当于从模块中获取一个不存在的属性,结果自然是undefined。

具体解决步骤

1. 修正i18n配置文件的导入语句

打开你的i18n配置文件,把以下导入代码:

const i18next = require("i18next").default;
const Backend = require("i18next-http-backend").default;
const i18nextMiddleware = require("i18next-http-middleware");

修改为:

const i18next = require("i18next");
const Backend = require("i18next-http-backend");
const i18nextMiddleware = require("i18next-http-middleware");

去掉.default后,就能正确获取到模块的实例了。

2. 完善i18next初始化配置(可选但推荐)

为了让语言检测功能更稳定,建议在init方法中添加detection配置项,明确语言检测的规则:

i18next
  .use(Backend)
  .use(i18nextMiddleware.LanguageDetector)
  .init({
    backend: {
      loadPath: __dirname + `/locales/{{lng}}/{{ns}}.json`,
    },
    fallbackLng: "en",
    preload: ["en"],
    detection: {
      order: ['querystring', 'cookie', 'header'], // 优先从URL参数、Cookie、请求头获取语言
      caches: ['cookie'] // 将用户选择的语言缓存到Cookie
    }
  });

3. 移除应用代码中的冗余导入

你的应用代码里直接导入了messages = require("../locales/en/translation.json"),但这个导入完全是冗余的——i18next会通过配置的loadPath自动加载对应语言的翻译文件,所以可以删掉这行代码。

验证修复效果

修改完成后,重新执行npm start启动应用,访问http://localhost:3000或者http://localhost:3000?lng=en,应该能正常返回greeting对应的翻译内容,不会再出现Cannot read property 'use' of undefined的错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 16:12:44