无法对未安装的组件执行 React 状态更新。取消 useEffect 中的所有任务

Can't perform a React state update on an unmounted component. Cancel all tasks in a useEffect

我看到的是一个常见错误,我尝试了不同的解决方案但没有结果。

到目前为止,这是我的代码,很少能正常工作,提取返回正确的电影数组,但大多数时候发回错误:

import React, { useState, useEffect } from "react";
import { Text, View, Image, ScrollView, ActivityIndicator } from "react-native";

function Dashboard() {
   const [loading, setLoading] = useState(true);
   const [popularMovies, setPopularMovies] = useState([])

   const popularMoviesUrl =
       ".....";

   const fetchMovies = () => {
    fetch(popularMoviesUrl)
     .then(res => res.json())
     .then(setPopularMovies)
     .then(console.log(popularMovies));
   };

   useEffect(() => {
       fetchMovies();
   }, []);

   const { results } = popularMovies;

      return loading ? (
         <View style={styles.loader}>
            <ActivityIndicator size="large" color="#dcae1d" animating />
         </View>
   ) : (
      <ScrollView horizontal style={styles.container}>
         {results.map(movie => (
            <View key={movie.id}>
            <Text style={styles.container}>{movie.title}</Text>
            <Image
                style={styles.poster}
                source={{
                    uri: `https://image.tmdb.org/t/p/w500${movie.poster_path}`
            }}
          />
        </View>
      ))}
      <Text>thfh</Text>
    </ScrollView>
   );
  }

  export default Dashboard;

引用从您的提取中返回的热门电影似乎是一个问题。将您的 popularMovies 状态设置为来自您的提取的 results 属性 而不是 JSON。

所以改变:

.then(setPopularMovies)

到...

.then(resJson => setPopularMovies(resJson.results))

然后删除结果变量并直接引用 popularMovies。