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

Expo SecureStore 认证后保存userId和token 后续仅可读取token问题

问题根因

  • SecureStore.setItemAsync 仅支持字符串类型的存储值,接口返回的userId为数字类型,直接传入会导致存储异常。
  • 你没有为异步存储方法添加await关键字,存储操作未完成就触发了页面跳转,出现了token已写入、userId还未写入的时序问题。

修复方案

调整登录逻辑代码,将userId转为字符串后存储,同时等待存储操作全部完成后再跳转页面,修改后代码如下:

const doUserLogIn = async() => {
    try {
      const response = await fetch('http://someurl-dev.de/api/login/?email='+email+'&password='+password, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json'
        }
      });
      const json = await response.json();
      // 等待存储完成,同时将数字类型userId转为字符串
      await SecureStore.setItemAsync('userid', String(json.userId));
      await SecureStore.setItemAsync('token', json.token);
    } catch (e) {
      alert('Error1:'+e);
    } finally {
      try{
        navigation.navigate('Schichten');
      } catch(e) {alert('Error2:'+e); }
    }
  }

读取注意事项

后续读取userId时如果需要使用数字类型,将读取到的字符串转回数字即可:

const userId = Number(await SecureStore.getItemAsync('userid'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:06:03