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

使用i18next-http-backend自定义request回调加载fr语言翻译失败求助

自定义i18next-http-backend的request函数时加载翻译失败:i18next::backendConnector错误

我正在尝试用i18next-http-backend从翻译微服务获取内容,现在只是在测试request参数里回调函数需要传入的对象格式,但一直遇到这个错误:i18next::backendConnector: loading namespace translations for language fr failed。

我的代码如下:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';

i18n.use(Backend)
  .use(initReactI18next)
  .init({
    backend: {
      crossDomain: false,
      withCredentials: false,
      overrideMimeType: false,
      requestOptions: {
        // used for fetch, can also be a function (payload) => ({ method: 'GET' })
        mode: 'cors',
        credentials: 'same-origin',
        cache: 'default'
      },
      request: function( options, url, callback, payload ) {
        callback( { test: 'Blah' }, { status: 200 } );
      },
      reloadInterval: false
    },
    lng: 'fr',
    fallbackLng: false,
    debug: true,
    ns: ['translations'],
    defaultNS: 'translations',
    react: {
      useSuspense: false,
      wait: true
    },
    interpolation: {
      escapeValue: false
    }
  });

export default i18n;

有没有人知道失败的原因?


问题原因及修复方案

这个错误的核心原因是你传给callback的参数格式完全不符合i18next的预期规则。

i18next-http-backend的request函数里,回调函数的参数逻辑是固定的:

  • 请求成功时:第一个参数必须传null/undefined(代表无错误),第二个参数才是包含翻译内容的对象
  • 请求失败时:第一个参数传错误对象,第二个参数传状态相关信息

你现在把翻译内容放在了第一个参数的位置,i18next会直接判定这是一个加载错误,自然就触发了那条失败提示。

修复后的代码

只需要调整request函数里的callback调用顺序,同时注意翻译数据的嵌套结构:

request: function( options, url, callback, payload ) {
  // 第一个参数传null表示请求无错误
  // 翻译数据必须放在data字段下,i18next会从这里读取资源
  callback( null, { 
    data: { test: 'Blah' },
    status: 200 
  });
}

额外注意点

翻译内容一定要嵌套在data属性里——这是i18next-http-backend约定的读取位置,如果直接把翻译对象作为第二个参数传递,i18next还是会找不到正确的资源。

修改完成后,你可以再打开debug模式验证:加载失败的错误日志会消失,test对应的翻译值也能正常被读取到。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:22:54