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

NextJS+TypeScript开发TMDB应用时useState赋值报错:void类型不可分配

问题解决:Argument of type 'void' is not assignable to parameter of type 'SetStateAction<{}>'

错误原因

你直接把异步函数getTrendMovies()的调用结果传给了setMoviesInfo,但异步函数默认返回Promise,且如果getTrendMovies内部没有return获取到的数据,它的返回值就是Promise<void>,这和setState要求的类型不匹配,触发类型错误。

步骤1:确保getTrendMovies正确返回数据

检查movies.ts中的函数,必须return接口返回的电影数据:

// movies.ts
export async function getTrendMovies() {
  const apiKey = '你的TMDB密钥';
  const res = await fetch(`https://api.themoviedb.org/3/trending/movie/day?api_key=${apiKey}`);
  
  if (!res.ok) throw new Error('获取热门电影失败');
  
  const movieData = await res.json();
  console.log(movieData); // 控制台能打印说明数据正常
  return movieData; // 关键:返回数据,否则函数返回Promise<void>
}

步骤2:在page.tsx中正确处理异步调用

不能直接把异步函数的结果传给setState,要在async回调中等待函数执行完成,再把数据传入setState:

// page.tsx
'use client'; // 必须加,因为使用了useState客户端钩子
import { useState } from 'react';
import { getTrendMovies } from './movies';

// 建议定义TS类型,避免any(可选但推荐)
interface Movie {
  id: number;
  title: string;
  poster_path: string;
}

interface TrendMoviesData {
  results: Movie[];
}

export default function Home() {
  // 初始化状态为null或空对象,根据实际返回结构调整
  const [moviesInfo, setMoviesInfo] = useState<TrendMoviesData | null>(null);

  // 封装异步获取逻辑
  const loadTrendMovies = async () => {
    try {
      const data = await getTrendMovies();
      setMoviesInfo(data); // 此时传入的是实际电影数据,类型匹配
    } catch (err) {
      console.error('加载失败:', err);
    }
  };

  return (
    <div>
      <button onClick={loadTrendMovies}>加载每日热门电影</button>
      
      {/* 根据状态生成电影卡片 */}
      {moviesInfo && (
        <div className="movie-grid">
          {moviesInfo.results.map(movie => (
            <div key={movie.id} className="movie-card">
              <h3>{movie.title}</h3>
              <img 
                src={`https://image.tmdb.org/t/p/w500${movie.poster_path}`} 
                alt={movie.title}
              />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

额外优化

给moviesInfo定义明确的TypeScript类型,可以提前发现类型错误,让代码更健壮,比如上面的TrendMoviesData和Movie接口。

内容的提问来源于stack exchange,提问作者Carlos Eduardo Diaz Torres

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:13:33