Publishing changes from within view updates is not allowed, this will cause undefined behavior.

I get the following error Publishing changes from within view updates is not allowed, this will cause undefined behavior.and do not get how to fix this issue. I already found out it should be to do something with @state, but I am new in swiftui.

Answered by bbatsell in 744183022

The problem is almost certainly with this line:

if ((authViewModel.currentUser?.id = collection.uid) != nil) {

I'm not sure if it's intentional, but that line is setting the AuthViewModel.currentUser.id, rather than checking for equality. If you want to check for equality, you need to use == and remove the != nil portion. Since you are setting the value, that observed object publishes a change while SwiftUI is calculating its view updates. If you are actually intending to set the value, then you should do it some other way — perhaps before this view is created, or, less optimally, in .onAppear.

Accepted Answer

The problem is almost certainly with this line:

if ((authViewModel.currentUser?.id = collection.uid) != nil) {

I'm not sure if it's intentional, but that line is setting the AuthViewModel.currentUser.id, rather than checking for equality. If you want to check for equality, you need to use == and remove the != nil portion. Since you are setting the value, that observed object publishes a change while SwiftUI is calculating its view updates. If you are actually intending to set the value, then you should do it some other way — perhaps before this view is created, or, less optimally, in .onAppear.

Publishing changes from within view updates is not allowed, this will cause undefined behavior.
 
 
Q