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

React使用useContext调用setPopup报Cannot read properties of undefined怎么解决

报错根因

你遇到的TypeError: Cannot read properties of undefined (reading 'setPopup')报错,本质是useContext(PopupContest)返回的结果为undefined,导致调用v.setPopup时读取不存在的属性。

具体解决步骤

1. 先核对Context导入的拼写错误

检查HomePage文件中导出的Context名称,你代码中引入的是PopupContest,大概率是拼写错误:正常Context命名通常为PopupContext,如果HomePage导出的是后者,拼写错误会直接导致引入的PopupContest为undefined,最终useContext返回空值。

2. 确认SFile组件被包裹在对应Context的Provider内部

useContext只能读取到上层最近的对应Provider传递的上下文值,如果SFile组件不在PopupContest.Provider的子组件树中,就会返回Context的默认值;如果创建Context时未指定默认值,默认值就是undefined。
你可以参考如下示例调整HomePage的代码:

// HomePage中创建Context的正确示例
import { createContext, useState } from 'react'
// 创建Context时建议传入兜底默认值,避免未包裹Provider时报错
export const PopupContest = createContext({
  setPopup: () => {},
  setSelectFile: () => {}
})

function HomePage() {
  const [popup, setPopup] = useState(0)
  const [selectFile, setSelectFile] = useState('')
  return (
    {/* 所有需要读取PopupContest的子组件必须放在Provider内部 */}
    <PopupContest.Provider value={{setPopup, setSelectFile}}>
      {/* 此处渲染你的列表以及SFile组件 */}
    </PopupContest.Provider>
  )
}

3. 调用方法前添加兜底判断

你可以使用JS可选链运算符?.做调用前的存在性判断,即使Context为空也不会抛出运行时报错,调整按钮点击事件代码如下:

<button 
  style={{'height':'50%', 'marginTop':'10px'}} 
  onClick={() => {
    v?.setPopup?.(6); 
    v?.setSelectFile?.(n.ident + "")
  }}
>
  X
</button>

4. 修复代码中其他潜在错误

你代码中let currentImg = c;的c变量未定义,后续运行会抛出c is not defined错误,需要替换为你实际的图片地址变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:45:02