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

React应用中Borsh反序列化报错this.buf.readUInt32LE不存在

Borsh反序列化报错问题原因及解决方案

错误根因

  • 抛出TypeError: this.buf.readUInt32LE is not a function错误的核心原因是Borsh库的反序列化逻辑默认依赖Node.js原生Buffer类型的内置方法,而浏览器原生仅支持Uint8Array类型,不存在readUInt32LE方法
  • 本地React项目使用的新版本构建工具(如Create React App v5+、Vite)默认移除了Node.js核心模块的polyfill,导致borsh.serialize返回的是普通Uint8Array实例,反序列化时无法识别对应方法
  • Codesandbox平台的运行环境默认内置了Node核心模块的polyfill,因此代码可正常运行

解决方案

方案1:全局挂载Buffer polyfill(通用方案)

  1. 安装Buffer依赖:
    npm install buffer
  2. 在项目入口文件(如src/index.js)最顶部添加如下代码,全局注入Buffer:
import { Buffer } from 'buffer';
window.Buffer = Buffer;
global.Buffer = Buffer;

方案2:调用反序列化前手动转换类型

无需全局修改,仅在业务代码处做类型转换即可,修改你的hello函数逻辑:

function hello() {
  const task = new Task({
    id: example.id,
    name: example.name,
    description: example.description,
    assignee: example.assignee,
    project_id: example.project_id,
    status: example.status
  });
  console.log(task);
  const uint8Buf = borsh.serialize(schema, task);
  // 新增转换逻辑,将Uint8Array转为Buffer实例
  const buf = Buffer.from(uint8Buf);
  console.log(buf);
  try {
    const newValue = borsh.deserialize(schema, Task, buf);
    console.log(newValue);
  } catch (error) {
    console.log(error);
  }
}

方案3:Vite项目额外配置

如果使用Vite构建项目,除安装buffer依赖外,还需在vite.config.js中添加如下配置:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'

export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    esbuildOptions: {
      define: {
        global: 'globalThis'
      },
      plugins: [
        NodeGlobalsPolyfillPlugin({
          buffer: true
        })
      ]
    }
  }
})

如果以上方案仍未解决问题,可尝试将borsh依赖降级到0.7.0版本测试,部分最新版本的borsh存在浏览器兼容适配问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:39:02