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

useEffect忽略getJobs调用,currentFilters变更时未更新currentJobs状态

问题根因

你的getJobs函数执行后返回的Promise虽然成功完成(fulfilled),但返回值为undefined,后续访问jobResponse.data时触发报错,你写了空的catch吞掉了所有错误,所以既看不到报错信息,then分支内的逻辑也不会执行。

排查步骤

  • 首先放开错误捕获,确认报错信息,把useEffect中的catch修改为:
    .catch(err => console.error('拉取数据失败:', err))
    
    如果打印出Cannot read properties of undefined (reading 'data'),即可确认是getJobs返回值异常的问题。
  • 检查getJobs函数的逻辑,90%以上的概率是漏写了return语句,以下是常见错误写法示例:
    // 错误1:async函数内没有返回请求结果
    const getJobs = async (filters) => {
      await axios.get('/api/jobs', { params: filters })
    }
    
    // 错误2:Promise链式写法没有返回请求实例
    const getJobs = (filters) => {
      axios.get('/api/jobs', { params: filters }).then(res => res.data)
    }
    
  • 修正getJobs的返回逻辑,参考正确写法:
    // 写法1:async/await版本
    const getJobs = async (filters: JobBoardFilters) => {
      const response = await axios.get('/api/jobs', { params: filters })
      return response
    }
    
    // 写法2:Promise链式版本
    const getJobs = (filters: JobBoardFilters) => {
      return axios.get('/api/jobs', { params: filters })
    }
    
    如果你在getJobs内部已经返回了response.data,则useEffect内直接赋值即可,不需要额外取.data:
    getJobs(currentFilters).then((jobResponse) => {
      console.log("Fetching data");
      setCurrentJobs(jobResponse);
    })
    
  • 补充验证:你当前控制台已经能打印Filters changed,说明currentFilters依赖触发正常,不需要额外调整useEffect的依赖项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:06:04