Model instance invalidated, backing data could no longer be found in the store

I have been recently getting the following error seemingly randomly, when an event handler of a SwiftUI view accesses a relationship of a SwiftData model the view holds a reference to. I haven't yet found a reliable way of reproducing it:

SwiftData/BackingData.swift:866: Fatal error: This model instance was invalidated 
because its backing data could no longer be found the store. 
PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: COREDATA_ID_URL),
implementation: SwiftData.PersistentIdentifierImplementation)

What could cause this error? Could you suggest me a workaround?

Update: the problem occurs when the app goes to the background, comes back, and SwiftUI tries to access relationships of SwiftData models that are direct input parameters to the View.

My app has a function that opens a URL in a browser, it is when you press the Back button and return from the browser to the app that this fatal error tends to occur.

When the app goes to the background, the BackingData of every relationship of this main model seems to get replaced with some subclass of "FutureBackingData". Accessing them results in the fatal error above.

Explicitly querying the relationship with @Query instead of relying on the relationship property seems to solve the problem.

It would be great to have some documentation on how exactly SwiftData is behaving when the app goes to the background.

It could be an issue with how you handle ModelContainer in your code or possibly how you handle your ModelContext object(s)

Model instance invalidated, backing data could no longer be found in the store
 
 
Q