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

使用jwt-decode解码JWT报错:无效base64,atob属性不存在

React Native中使用jwt-decode解码JWT Token报错:InvalidTokenError (Property 'atob' doesn't exist)

问题详情

我在学习Code with Mosh的React Native在线课程时,实现认证授权环节遇到问题:本地部署的服务器返回的JWT Token能在jwt.io正常解码出用户信息,但用jwt-decode库解码时抛出错误:

Warning: An unhandled error was caught from submitForm() [InvalidTokenError: Invalid token specified: invalid base64 for part #2 (Property 'atob' doesn't exist)]

相关代码片段:

import React, { useState, useContext } from "react";
import { Image, StyleSheet } from "react-native";
import * as Yup from "yup";
import { jwtDecode } from "jwt-decode";

const handleSumbit = async ({ email, password }) => {
const result = await authApi.login(email, password);
if (!result.ok) return setLoginFailed(true);
setLoginFailed(false);

const token = result.data;
const decoded = jwtDecode(token);
console.log(decoded);
};

问题原因

jwt-decode默认依赖浏览器环境的atob()函数解码base64,但React Native的全局环境中没有这个浏览器API,导致解码失败。而jwt.io运行在浏览器中,所以能正常处理Token。

解决方案

方案1:添加全局Polyfill

在项目入口文件(如App.js)或当前组件顶部,手动定义atob和btoa的兼容实现:

// 适配React Native的base64编码/解码
global.atob = (data) => Buffer.from(data, 'base64').toString('binary');
global.btoa = (data) => Buffer.from(data, 'binary').toString('base64');

之后就能正常调用jwtDecode(token)解码。

方案2:使用jwt-decode的自定义解码选项

直接给jwtDecode传入自定义的base64解码函数,无需修改全局变量:

const decoded = jwtDecode(token, {
  base64Decode: (str) => Buffer.from(str, 'base64').toString('utf8')
});

方案3:替换为RN兼容的JWT库

如果上述方法仍有问题,可以改用react-native-jwt这类专门适配React Native的JWT处理库,不过前两种方案已经足够解决大部分场景的问题。

验证

修改代码后重新运行,解码操作应该能正常返回预期的用户信息对象{user: name, ...}。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:10:07