Change matrixblock field value before save element
After a bit of testing, it appears you don't have anything to do to have your values saved, just set them and Craft will take care of the rest.
    Event::on(
        Elements::class,
        Elements::EVENT_BEFORE_SAVE_ELEMENT,
        static function (ElementEvent $event) {
            $element = $event-&gt;element;
            if ($element instanceof Entry &amp;&amp; $element-&gt;getSection()-&gt;handle === 'testSection') {
                /** @var MatrixBlock[] $blocks */
                $blocks = $element-&gt;getFieldValue('testMatrix')-&gt;all();
                foreach ($blocks as $block) {
                    $block-&gt;setFieldValue('automaticField', uniqid('some unique value', false));
                }
            }
        }