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

React Context API报错:Uncaught TypeError,无法解构useStateValue返回值

解决React Context API解构时的"undefined is not iterable"错误

问题场景

执行const [{user}, dispatch] = useStateValue();时触发以下错误:

Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

使用React Context API搭建全局状态层,期望用户登录后将信息存入状态,但在解构自定义hook返回值时出错。

相关代码

Header组件代码

const Header = () => {
  const firebaseAuth = getAuth(app);
  const provider = new GoogleAuthProvider();
  const [{user}, dispatch] = useStateValue(); 

  const login = async () =>{
    const {
      user: { refreshToken, providerData },
    } = await signInWithPopup(firebaseAuth, provider);
    dispatch({
      type: actionType.SET_USER,
      user: providerData[0],
    });
  };

Context状态管理代码

import React, { createContext, useContext, useReducer } from "react";
export const StateContext = createContext();
export const StateProvider = ({ reducer, initialState, children }) => (
  // initial state is already defined as user : null
  // children is basically our component
  <StateContext.Provider value={useReducer(reducer, initialState)}>
    {children}
  </StateContext.Provider>
);
// Custome Hook
export const useStateValue = () => {
  useContext(StateContext);
};

错误根源

自定义hook useStateValue 内部调用了useContext(StateContext)但没有返回结果,导致调用该hook时得到undefined。而解构语法const [x, y] = ...要求右侧是可迭代对象(这里useReducer返回的是包含状态和dispatch函数的数组),对undefined进行解构就会触发上述错误。

修复方法

修改useStateValue hook,让它返回useContext(StateContext)的结果:

// 修复后的自定义Hook
export const useStateValue = () => {
  return useContext(StateContext);
};
// 或者简写为
export const useStateValue = () => useContext(StateContext);

修复后,useStateValue()会正确返回useReducer生成的[state, dispatch]数组,解构操作就能正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:35:27