Modify Prefab Asset in OnValidate

I’m trying to automatically assign a value to a field on a component that resides in a prefab in script and save that prefab modification in OnValidate.

Here is my script:

 [SerializeField] MyComponent myComponent;
 void OnValidate()
     if (myComponent != null)
         myComponent.myScriptableObject = this;
//At this point, myComponent.myScriptableObject shows the correct value
         PrefabUtility.SavePrefabAsset(myComponent.gameObject, out bool success);
//Now myComponent.myScriptableObject is reset to null

Unfortunately, this script doesn’t work. For some reason the value is not actually applied to the prefab. What am I missing here?

Also, calling SavePrefabAsset() in Onvalidate gives me the following error in console :

Destroying GameObjects immediately is not permitted during physics trigger/contact, animation event callbacks or OnValidate. You must use Destroy instead.
UnityEditor.PrefabUtility:SavePrefabAsset(GameObject, Boolean&) (at ?)

Is this related in any way?

In case others were looking for that answer. This is what I ended up doing:

SerializedObject serializedObject = new SerializedObject(myComponent);
SerializedProperty myComponentProperty = serializedObject.FindProperty("myProperty");
if (myComponentProperty != null)
    	myComponentProperty.objectReferenceValue = this;

What are you actualy trying to do? There’s something fishy about what you showed …