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

React Reanimated 3中“仅UI运行时可直接读取_value”错误修复

修复React Native Reanimated的「Reading from _value directly is only possible on the UI runtime」错误

错误原因

这个错误的核心是线程上下文不匹配:onPress回调运行在JS线程中,但withRepeat、withTiming这类Reanimated动画函数是UI线程专属的API,直接在JS线程中调用并赋值给sharedValue会触发线程访问权限错误。

修复方案

将动画赋值逻辑包裹在runOnUI中,强制代码在UI线程执行,同时补全缺失的API导入:

修复后的完整代码

import Animated, { useSharedValue, useAnimatedStyle, withRepeat, withTiming, runOnUI } from 'react-native-reanimated';
import { Button, StyleSheet } from 'react-native';

function WobbleExample(props) {
  const rotation = useSharedValue(0);

  const animatedStyle = useAnimatedStyle(() => {
    return {
      transform: [{ rotateZ: `${rotation.value}deg` }],
    };
  });

  return (
    <>
      <Animated.View style={[styles.box, animatedStyle]} />
      <Button
        title="wobble"
        onPress={() => {
          runOnUI(() => {
            rotation.value = withRepeat(withTiming(10), 6, true);
          })();
        }}
      />
    </>
  );
}

const styles = StyleSheet.create({
  box: {
    width: 100,
    height: 100,
    backgroundColor: '#2196F3',
    margin: 32,
  },
});

关键注意点

  • 必须导入所有用到的Reanimated API:之前的代码遗漏了withRepeat、withTiming、runOnUI
  • runOnUI返回的是一个函数,需要加()立即执行才能触发UI线程逻辑
  • 所有动画相关的函数调用(withTiming、withRepeat等)都必须放在UI线程环境中(比如useAnimatedStyle回调、runOnUI包裹的函数内)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:02:16