Loose chain is usually the problem.
Too loose, worn bar, or bad cutting technique.
First, check tension. A chainsaw chain shouldn’t sag on the bottom of the guide bar. You should be able to pull the chain up and see about 1/8 inch (3mm) of the drive links visible in the bar groove. If it’s sagging, tighten it. That alone fixes 80% of derailments.
Second, look at the bar rails. If they’re worn unevenly (like a ridge on the inside edge), the chain will walk off. Flip the bar regularly or replace it when it’s too far gone. Also make sure the bar groove isn’t packed with sawdust.
Third, check the sprocket nose (if your bar has one) and the drive sprocket on the saw. Worn sprockets let the chain slip. And a dull chain bounces, which can pop it off the bar. Keep it sharp.
A well-maintained chain doesn’t come off.