Alignment, alignment, alignment & tension, tension, tension.
As Trye said, the sprockets must be aligned perfectly so the chain runs in a straight line between them. No lateral offset. The tensioner wheel must also align with the chain path. Often the tensioner bracket must be bent or twisted to achieve this.
Lay a straight edge against the sprockets. The edge must lay flush against both sides of the sprockets.
If the rear sprocket wobbles or is not concentric with the hub that too will cause chain derailing problems.
Lots to read here on chain/sprocket alignment. Try the search feature and you'll have plenty to read on the subject.
Tom