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

React Native中jwt-decode调用报错:_jwtDecode.default不是函数

问题描述

在React Native项目中编写index.js,尝试从AsyncStorage获取登录用户的authToken,再用jwt-decode解析token提取userId,但运行时报错:

Error fetching user: [TypeError: 0, _jwtDecode.default is not a function (it is undefined)]

日志显示已成功获取token,但解析步骤失败。尝试重新安装jwt-decode(曾误写为jet-decode),问题仍未解决。

项目代码

import { StyleSheet, Text, View } from "react-native";
import React, { useEffect, useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import jwt_decode from "jwt-decode";
import axios from "axios";

const index = () => {
  const [userId, setUserId] = useState("");
  const [user, setUser] = useState();

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const token = await AsyncStorage.getItem("authToken");
        if (!token) {
          console.log("No token found");
          return;
        }
        console.log("Token retrieved:", token);

        const decodedToken = jwt_decode(token);
        console.log("Decoded token:", decodedToken);

        const userId = decodedToken.userId;
        if (!userId) {
          console.log("No userId in token");
          return;
        }
        setUserId(userId);
      } catch (error) {
        console.log("Error fetching user:", error);
      }
    };
    fetchUser();
  }, []);

  useEffect(() => {
    console.log("userId:", userId);
  }, [userId]);

  return (
    <View>
      <Text>index</Text>
    </View>
  );
};

export default index;

const styles = StyleSheet.create({});

运行日志

LOG userId:
LOG Token retrieved:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NjdhYWEyODhlOWZiNTAxMDExMmQwNTIiLCJpYXQiOjE3MTk0ODIzMTl9.RB6ZVFQRv8Q2s_zrKljEUQP1EKt42Od7qyHZjTGOZAU
LOG Error fetching user: [TypeError: 0, _jwtDecode.default is not a function (it is undefined)]

解决方案

1. 修正jwt-decode的导入方式

jwt-decode从v3版本开始采用命名导出,不再支持默认导出。将代码中的导入和调用逻辑修改如下:

// 替换原导入语句
import { jwtDecode } from "jwt-decode";

// 替换解析token的代码
const decodedToken = jwtDecode(token);

2. 确保正确安装依赖

之前误写包名为jet-decode,先卸载错误的包(如果已安装),再重新安装正确的依赖:

npm uninstall jet-decode
npm install jwt-decode
# 或使用yarn
yarn remove jet-decode
yarn add jwt-decode

3. 清除React Native缓存

缓存可能导致模块未更新,重启metro服务并清除缓存:

npx react-native start --reset-cache

完成以上步骤后重新运行项目,即可正常解析token并提取userId。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:34:56