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

React Native Animated报错:TypeError: Cannot read property 'apply' of undefined

问题解决:React Native Animated 报错 "Cannot read property 'apply' of undefined"

核心原因

你在setTimeout里犯了一个常见错误:直接执行fadeIn()并把返回值传给了setTimeout,而非传递函数本身的引用。

fadeIn()执行后要么返回null(当fadeStarted为true时),要么返回undefined(函数无显式return时),setTimeout会在1.5秒后尝试调用这个返回值,但null/undefined不是可执行函数,因此抛出"Cannot read property 'apply' of undefined"错误。

修正方案

1. 修复setTimeout调用

将setTimeout(fadeIn(), 1500)改为传递函数引用:

useEffect(() => {
  setTimeout(fadeIn, 1500)
}, [])

2. 简化冗余状态

由于空依赖的useEffect仅在组件挂载时执行一次,fadeStarted状态完全多余,可以直接删除,简化fadeIn函数:

const fadeIn = () => {
  Animated.timing(fade, {
    toValue: 1,
    duration: 4000,
    useNativeDriver: true
  }).start();
};

完整修正后代码示例

import React, { useEffect } from 'react';
import { Animated, Text, View } from 'react-native';

export default function YourComponent() {
  const fade = new Animated.Value(0);

  const fadeIn = () => {
    Animated.timing(fade, {
      toValue: 1,
      duration: 4000,
      useNativeDriver: true
    }).start();
  };

  useEffect(() => {
    setTimeout(fadeIn, 1500)
  }, [])

  return (
    <Animated.View style={{opacity: fade, marginTop: 55, justifyContent: 'center', alignItems: 'center'}}>
      <Text style={{fontFamily: 'Gilroy-ExtraBold', color: "#28DE19", fontSize: 40, textAlign: 'center'}}>Kingdom of William</Text>
      <Text style={{fontFamily: 'Gilroy-SemiBold', color: "#28DE19", fontSize: 20, textAlign: 'center'}}>(Get it?)</Text>
    </Animated.View>
  )
}

补充说明

  • 传fadeIn()时函数会立即执行,而非等待1.5秒,这也是你看到淡入效果提前触发、之后才报错的原因。
  • 空依赖useEffect仅在组件首次挂载时运行一次,无需额外状态防止重复触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:35:13