NextJS 13 App Router页面异步调用出现React运行时错误求助
问题原因与解决方案
你遇到的报错核心原因是:加了'use client'的客户端组件不能定义为async函数。
Next.js 13 App Router中,服务器组件(默认无'use client'标记)支持直接用async/await异步获取数据,但客户端组件的渲染逻辑是同步的,不能返回Promise,因此会抛出"Objects are not valid as a React child (found: [object Promise])"错误——尽管你的接口请求能成功打印数据,但组件本身变成了Promise对象,无法被React正常渲染。
方案1:改为服务器组件(推荐,符合官方文档用法)
直接移除'use client'标记,让Home组件成为服务器组件,即可正常使用async/await获取数据:
const getPlaces = async () => { const res = await fetch(`${process.env.NEXT_PUBLIC_LOCAL_URL}/api/places`, {cache: 'no-store'}); if (!res.ok) { throw new Error('Failed to fetch data'); } return res.json(); } const Home = async () => { const places = await getPlaces(); console.log(places); return ( <div className={'text-left'}>Homepage</div> ) }; export default Home;
方案2:保留客户端组件(需处理异步逻辑)
如果必须使用客户端组件(比如需要用到React Hooks、客户端交互),则需要用useEffect + useState来处理异步请求,或者使用SWR/React Query这类数据获取库:
'use client'; import { useState, useEffect } from 'react'; const getPlaces = async () => { const res = await fetch(`${process.env.NEXT_PUBLIC_LOCAL_URL}/api/places`, {cache: 'no-store'}); if (!res.ok) { throw new Error('Failed to fetch data'); } return res.json(); } const Home = () => { const [places, setPlaces] = useState(null); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const data = await getPlaces(); setPlaces(data); console.log(data); } catch (err) { setError(err instanceof Error ? err.message : 'Unknown error'); } }; fetchData(); }, []); if (error) return <div>Error: {error}</div>; if (!places) return <div>Loading...</div>; return ( <div className={'text-left'}>Homepage</div> ) }; export default Home;
内容的提问来源于stack exchange,提问作者Axiol
相关产品推荐
相关产品推荐

