Change material during rendering / frame_change [crash]

Hey, I’m trying to change material on many objects during frame change with python.
In viewport everything works fine but during Animation Rendering(cycles or eevee) it crashes immediately or a few frames later.

My system can’t handle more than 500 cubes. A small delay in foreach is also no solution. Does anyone have an idea? (Ps. Shader animation is no option)

It crashes during rendering with this Error: EXCEPTION_ACCESS_VIOLATION

import bpy

scene = bpy.context.scene
objs = [obj for obj in scene.objects if obj.type == 'MESH']
m =
mats = [m['Red'], m['Green'], m['Blue']]

def frame_change_post(scene, depsgraph):
    nr = scene.frame_current % 3
    print("Frame Change: ", nr)
    for obj in objs:
        obj.active_material = mats[nr]