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

React Native:生物识别认证场景下解构非可迭代实例错误排查

问题排查:React Native Context解构错误导致"Invalid attempt to destructure non-iterable instance"

问题场景与错误提示

开发支持生物识别与PIN码认证的React Native应用时,在PinScreen中完成验证后调用setAuthenticated(true),触发以下错误:

Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.

相关核心代码如下:

App.js 核心代码

import { AuthContext } from './contexts/AuthContext';

const App = () => {
  const [authenticated, setAuthenticated] = useState(false);

  // 其他初始化逻辑...

  return (
    <AuthContext.Provider value={{ authenticated, setAuthenticated }}>
      {/* 导航容器与路由配置 */}
    </AuthContext.Provider>
  );
}

PinScreen 核心错误代码

const PinScreen = () => {
    // 错误的解构方式
    const [authenticated, setAuthenticated] = useContext(AuthContext);

    const onAuthenticate = () => {
        LocalAuthentication.authenticateAsync().then(auth => {
            if (auth.success) {
                setAuthenticated(true);
                // 页面跳转逻辑
            }
        });
    }

    // 其他交互逻辑...
}

错误原因

Context传递的值类型与解构语法不匹配:

  • App.js中通过AuthContext.Provider传递的是对象类型的上下文值:{ authenticated, setAuthenticated }
  • PinScreen中错误使用了数组解构语法读取对象,而对象不具备数组的迭代器特性,因此抛出迭代错误。

解决方法

将PinScreen中的数组解构替换为对象解构,匹配上下文值的类型:

// 修改后的正确代码
const { authenticated, setAuthenticated } = useContext(AuthContext);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:20:41