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

应用仅显示加载界面且报AsyncStorage相关TypeError问题求助

解决React Native中AsyncStorage未定义导致的加载停滞问题

你的问题根源在于AsyncStorage的导入方式错误,同时缺少Promise错误捕获,导致代码执行中断,界面一直停留在加载状态。

问题分析

控制台警告TypeError: undefined is not an object (evaluating '_asyncStorage.AsyncStorage.getItem')明确说明:调用AsyncStorage.getItem时,AsyncStorage本身是undefined。这是因为@react-native-async-storage/async-storage新版本中,AsyncStorage是默认导出,而非命名导出,你用{ AsyncStorage }的方式导入会获取到无效值。

另外,tryLogin异步函数没有错误捕获逻辑,一旦执行出错(比如导入错误导致的调用失败),Promise会被拒绝但未处理,进一步卡住代码流程。

修复步骤

  1. 修正AsyncStorage导入方式
    把命名导入改成默认导入:
// 错误写法
import { AsyncStorage } from '@react-native-async-storage/async-storage';

// 正确写法
import AsyncStorage from '@react-native-async-storage/async-storage';
  1. 添加错误捕获逻辑
    在tryLogin函数中加入try/catch块,处理可能的错误,避免Promise未处理警告,同时保证代码流程能正常推进。

修改后的完整代码

import React, { useEffect } from 'react';
import { View, ActivityIndicator, StyleSheet} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage'; // 修正导入

import { useDispatch } from 'react-redux';

import Colors from '../constants/Colors';
import * as authActions from '../store/actions/auth';

const StartupScreen = props => {
    const dispatch = useDispatch();

    useEffect(() => {
        const tryLogin = async () => {
            try { // 添加错误捕获
                const userData = await AsyncStorage.getItem('userData');
                if (!userData) {
                    dispatch(authActions.setDidTryAutoLogin());
                    return;
                }
                const transformedData = JSON.parse(userData);
                const { token, user } = transformedData;

                dispatch(authActions.authenticate(user, token));
            } catch (err) {
                // 可添加自定义错误处理,比如打印日志、导航到登录页
                console.log('自动登录失败:', err);
                dispatch(authActions.setDidTryAutoLogin());
            }
        };

        tryLogin();
    }, [dispatch])

    return (
        <View style={styles.screen}>
            <ActivityIndicator size="large" color={Colors.primary} />
        </View>
    );
};

const styles = StyleSheet.create({
    screen: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
});

export default StartupScreen;

额外说明

  • 若你是升级了@react-native-async-storage/async-storage库,需注意旧版本的命名导出已被移除,必须使用默认导入。
  • 添加错误捕获后,即便自动登录过程中出现其他问题(如存储数据损坏),界面也不会一直卡在加载状态,能正常跳转到对应页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:40:24