Nextjs与Sanity项目中setAllCategories is not a function报错排查
问题解决:Error: setAllCategories is not a function
核心错误原因
你对useState的返回值用了对象解构,但useState实际返回的是一个数组,这直接导致setAllCategories被解析为undefined,所以会报“不是函数”的错误。
修正后的代码
把useState的解构方式从对象改成数组即可,同时可以优化初始值为[](空数组),避免后续判断的冗余:
import React, { useEffect, useState } from 'react'; import sanityClient from '../pages/client.js'; const Categories = () => { // 改为数组解构,初始值设为空数组更合理 const [allCategories, setAllCategories] = useState([]); useEffect(() => { sanityClient.fetch( `*[_type == "category"]{ title, _id // 建议加上_id,用来做map的唯一key }` ) .then((data) => setAllCategories(data)) .catch(console.error); }, []) return ( <div> <h2>Categories</h2> <div> {/* 初始值是空数组,可直接map,无需额外判断 */} {allCategories.map((category) => ( <p key={category._id}>{category.title}</p> ))} </div> </div> ) } export default Categories
额外优化建议
- 初始值用空数组
[]替代null:组件首次渲染时allCategories就是可遍历的数组,省去allCategories &&的判断逻辑。 - 用Sanity文档的
_id作为key:避免使用数组index作为key,当数组元素顺序变化时,index会导致React错误复用组件,而_id是每个文档的唯一标识,更可靠。
你的Category Schema没有问题,无需修改。
内容的提问来源于stack exchange,提问作者Remo Furrer
相关产品推荐
相关产品推荐

