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

TypeScript项目fetch接口数据后setNft赋值state报void类型不兼容错误

错误原因

你代码里的Promise链式调用存在返回值问题:

  • 第二个then里执行了console.log(result),console.log方法的返回值是void类型,这个值会作为返回值传递到下一个then的入参data里
  • 所以第三个then拿到的data实际是void类型,自然不符合setNft要求的SetStateAction<Anu | undefined>类型,就抛出了对应的类型错误

另外还有一个隐藏的类型问题:fetch返回的res.json()默认是unknown类型,就算你确认返回结构符合Anu,也需要显式做类型标注,不然TS也可能抛出类型不匹配的错误。

解决方案

直接把打印逻辑和赋值逻辑合并到同一个then里即可,不需要拆分多个then,同时给返回数据加上类型断言:

const [nft, setNft] = useState<Anu>()

useEffect(() => {
  fetch("http://51.15.56.157:3000/anu/5000")
    .then((res) => res.json())
    .then((result) => {
      console.log(result)
      setNft(result as Anu) // 合并逻辑 + 显式类型断言
    })
}, [])

如果你确实需要拆分多个then,就需要在上一个then里把结果显式return出去:

useEffect(() => {
  fetch("http://51.15.56.157:3000/anu/5000")
    .then((res) => res.json())
    .then((result) => {
      console.log(result)
      return result // 显式返回结果给下一个then
    })
    .then((data) => setNft(data as Anu))
}, [])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:36:03