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

React与Next.js中setState is not a function错误排查求助

问题分析与修复

你的错误根源在于useState的解构方式错误:React的useState Hook返回的是一个包含状态值和更新函数的数组,而非对象,你误用了对象解构语法,导致setCourse和setLoading被解析为undefined,调用时自然会报“setState is not a function”错误。

修正后的首页代码

"use client";
import { useState, useEffect } from "react";
import Loading from "./loading";
import Link from "next/link";
import Courses from "./components/courses";

export default function HomePage() {
  // 改为数组解构,这是useState的正确用法
  const [course, setCourse] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchCourses() {
      const res = await fetch("/api/courses");
      const data = await res.json();
      setCourse(data);
      setLoading(false);
    }
    fetchCourses();
  }, []);

  if (loading) {
    return <Loading />;
  }

  return (
    <div>
      <h1>Welcome to next website</h1>
      <Courses courses={course} />
    </div>
  );
}

组件代码说明

你的Courses组件写法没有问题,使用可选链courses?.map能避免空数组或undefined时的报错,逻辑是合理的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 15:42:03