【问题标题】:Modifying state from inside .onAppear causes error 'Modifying state during view update, this will cause undefined behavior'从 .onAppear 内部修改状态会导致错误“在视图更新期间修改状态,这将导致未定义的行为”
【发布时间】:2021-01-10 08:05:45
【问题描述】:

在真实设备上测试时,我收到以下代码的Modifying state during view update, this will cause undefined behavior 问题。在 iPhone 11 上测试。在模拟器上,问题没有出现,代码按预期工作。

what I can gather从.onAppear内部修改状态就可以了。

这里发生了什么?为什么会出现此错误?

struct Clouds: View {
    @State private var cloudOffset: CGFloat = 0.0
    @State private var cloudOffset2: CGFloat = 0.0

    @EnvironmentObject var mainData: MainData
    
    var body: some View {
        GeometryReader { geo in
            if mainData.animateClouds {
                Image("cloudsBlurry")
                    .resizable()
                    .scaledToFit()
                    .offset(x: self.cloudOffset, y: 0.0)
                    .onAppear {
                        let baseAnimation = Animation.linear(duration: 30)
                        let repeated = baseAnimation.repeatForever(autoreverses: true)

                        withAnimation(repeated) {
                            self.cloudOffset += geo.size.width * 0.50 //Error here
                        }
                    }
                Image("cloudsBlurry3")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(height: geo.size.height * 2)
                    .offset(x: self.cloudOffset2, y: 0.0)
                    .onAppear {
                        let baseAnimation = Animation.linear(duration: 30)
                        let repeated = baseAnimation.repeatForever(autoreverses: true)
                        
                        self.cloudOffset2 = -geo.size.width //Error here
                        
                        withAnimation(repeated) {
                            self.cloudOffset2 += geo.size.width * 0.50 //Error here
                        }
                    }
            } else {
                Image("cloudsBlurry")
                    .resizable()
                    .scaledToFit()
                    .offset(x: 0.0, y: 0.0)
            }
        }
    }
}

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    您有循环,因为offset(x: self.cloudOffset 依赖和self.cloudOffset += geo 由于上述依赖而强制刷新。

    尝试以位延迟进行更新,以使当前刷新以当前偏移值完成:

    withAnimation(repeated) {
        DispatchQueue.main.async {
           self.cloudOffset += geo.size.width * 0.50
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 2020-03-11
      • 2020-05-15
      • 2023-02-06
      • 2022-11-13
      • 2020-10-27
      • 2021-12-18
      • 2020-06-12
      • 2019-12-11
      相关资源
      最近更新 更多