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

React Native TypeScript中使用Joi库遇TextEncoder缺失错误求助

React Native中使用Joi遇到TextEncoder不存在及Schema undefined问题的解决办法

解决ReferenceError: Property 'TextEncoder' doesn't exist错误

Joi 17+版本依赖Node.js环境的TextEncoder API,但React Native的Hermes引擎默认未提供该API,可通过以下两种方式解决:

  1. 添加polyfill

    • 安装text-encoding包:
      npm install text-encoding --save
      # 或使用yarn
      yarn add text-encoding
      
    • 在项目入口文件(如index.js或App.js)最顶部添加代码,将polyfill挂载到全局:
      import { TextEncoder, TextDecoder } from 'text-encoding';
      global.TextEncoder = TextEncoder;
      global.TextDecoder = TextDecoder;
      
  2. 降级Joi版本
    Joi 16.x版本对环境依赖更低,无需额外polyfill,直接安装即可:

    npm install joi@16 --save
    # 或使用yarn
    yarn add joi@16
    

解决Joi Schema显示undefined的问题

  1. 检查Joi导入方式是否正确:

    • ES模块环境(React Native默认支持)使用:
      import Joi from 'joi';
      
    • CommonJS环境使用:
      const Joi = require('joi');
      
  2. 确认Schema定义语法无拼写错误:

    // 正确的Schema示例
    const userSchema = Joi.object({
      name: Joi.string().required(),
      email: Joi.string().email().required()
    });
    
  3. 保证Schema定义在使用它之前,避免因执行顺序问题导致未定义。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:30:47